Tools工具包-窗体分配
当前系列所有demo下载地址:
https://github.com/GaoRenBao/OpenCv4-Demo
https://gitee.com/fuckgrb/OpenCv4-Demo
平时使用cv2.imshow()的时候,如果窗口数2个以上,便会重叠在一起。
这个包,会合理管理窗口的大小和位置,使之不重叠。
目前只有python版本!!
opencv_windows_management.py
import cv2, math
import tkinter as tk
class Window:
def __init__(self, name, image, weight=1):
self.name = name
self.image = image.copy()
self.weight = weight
self.shape = self.image.shape
self.hight_x = self.shape[0]
self.lenght_y = self.shape[1]
class opencv_windows_management:
def __init__(self):
self.windows = dict()
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
self.screen_size = (screen_width, screen_height) # (1280, 800)
root.quit()
def add(self, name, image, weight=1):
'''
权重,越高,图片显示越大
:return:
'''
cv2.namedWindow(name, flags=cv2.WINDOW_AUTOSIZE)
window = Window(name, image, weight)
self.windows[name] = window
# self.windows[name] = image
def show(self):
lenw = len(self.windows)
w_l = int(self.screen_size[0] / lenw)
max_num_line = math.ceil(math.sqrt(lenw)) # 取平方根
# TODO 权重
for i, name in enumerate(self.windows):
# if (i+1) >max_num_line:
# #TODO 换行
# cv2.moveWindow(name, w_l * i, h_x*j)
# pass
win = self.windows[name]
image = win.image
# image = self.windows[name]
# h_x = int(image.shape[1] / w_l * image.shape[0]) #保持比例
h_x = int(w_l / win.lenght_y * win.hight_x) # 保持比例
# print((w_l,h_x))
img2 = cv2.resize(image, (w_l, h_x))
cv2.moveWindow(name, w_l * i, 0)
cv2.imshow(name, img2)
使用方法demo1:
import cv2
import numpy as np
import os
import errno
from opencv_windows_management import opencv_windows_management
cvwm = opencv_windows_management()
path = '../images/messi5.jpg'
if not os.path.exists(path):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path)
img = cv2.imread(path, cv2.IMREAD_UNCHANGED) # 包括图像的 alpha 通道
print(img.shape)
# cv2.imshow('src', img)
cvwm.add('src', img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# cv2.imshow('gray', gray)
cvwm.add('gray', gray)
ret, thresh1 = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
cvwm.add('thresh1', thresh1)
cvwm.show()
cv2.waitKey(0)
使用方法demo2:
import cv2
from opencv_windows_management import opencv_windows_management
cvwm = opencv_windows_management()
cap = cv2.VideoCapture(0)
# ret = cap.set(3, 640)
# ret = cap.set(4, 480)
#
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
while cap.isOpened():
ret, frame = cap.read()
frame = cv2.flip(frame, flipCode=1)
cvwm.add('frame', frame)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# cv2.imshow('frame', gray)
cvwm.add('gray', gray)
#人脸识别
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
print("Detected ", len(faces), " face")
for (x, y, w, h) in faces:
face = gray[y:y + h, x:x + w]
cvwm.add('face', face)
cvwm.show()
if cv2.waitKey(delay=1) == ord("q"):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()