- 颜色检测功能
- UI界面编写
一、代码实现
通过鼠标回调函数获取当前鼠标的坐标值,获取其像素值(rgb格式,数值范围为0~255),并转化其他格式的数值,如YCrCb、Lab、HSV,并通过占位符在窗口中显示颜色数值。
import cv2
import glob
import numpy as np
# 鼠标回调函数
def showPixelValue(event, x, y, flags, param):
global img, combinedResult, placeholder
if event == cv2.EVENT_MOUSEMOVE:
# 获取鼠标所在(x,y)位置的像素值
bgr = img[y, x]
# 将BGR线束转换为其他颜色格式
ycb = cv2.cvtColor(np.uint8([[bgr]]), cv2.COLOR_BGR2YCrCb)[0][0]
lab = cv2.cvtColor(np.uint8([[bgr]]), cv2.COLOR_BGR2Lab)[0][0]
hsv = cv2.cvtColor(np.uint8([[bgr]]), cv2.COLOR_BGR2HSV)[0][0]
# 创建一个空占位符以显示值
placeholder = np.zeros((img.shape[0], 400, 3), dtype=np.uint8)
# 使用颜色空间的值填充占位符
cv2.putText(placeholder, "BGR {}".format(bgr), (20, 70), cv2.FONT_HERSHEY_COMPLEX, .9, (255, 255, 255), 1,
cv2.LINE_AA)
cv2.putText(placeholder, "HSV {}".format(hsv), (20, 140), cv2.FONT_HERSHEY_COMPLEX, .9, (255, 255, 255), 1,
cv2.LINE_AA)
cv2.putText(placeholder, "YCrCb {}".format(ycb), (20, 210), cv2.FONT_HERSHEY_COMPLEX, .9, (255, 255, 255), 1,
cv2.LINE_AA)
cv2.putText(placeholder, "LAB {}".format(lab), (20, 280), cv2.FONT_HERSHEY_COMPLEX, .9, (255, 255, 255), 1,
cv2.LINE_AA)
# 将两个结果组合在一个图像中并排显示
combinedResult = np.hstack([img, placeholder])
cv2.imshow('PRESS P for Previous, N for Next Image', combinedResult)
def color_detect_function(instance):
# 导入图片并绑定鼠标回调函数
global img
img=instance.color_det_original[0][0]
files = glob.glob(img)
files.sort()
img = cv2.imread(files[0])
img = cv2.resize(img, (400, 400))
cv2.imshow("PRESS P for Previous, N for Next Image", img)
# 创建一个空窗口
cv2.namedWindow('PRESS P for Previous, N for Next Image')
# 设置鼠标回调函数
cv2.setMouseCallback('PRESS P for Previous, N for Next Image', showPixelValue)
i = 0
while (1):
k = cv2.waitKey(1) & 0xFF
# 在文件夹下检查下一张图片
if k == ord('n'):
i += 1
img = cv2.imread(files[i % len(files)])
img = cv2.resize(img, (400, 400))
cv2.imshow('PRESS P for Previous, N for Next Image', img)
# 在文件夹下检查前一张图片
elif k == ord('p'):
i -= 1
img = cv2.imread(files[i % len(files)])
img = cv2.resize(img, (400, 400))
cv2.imshow('PRESS P for Previous, N for Next Image', img)
elif k == 27:
cv2.destroyAllWindows()
break
二、UI编写
""""""""""""" 颜色检测"""""""""""""
# 创建一个窗口,定义位置,标题等属性
instance.widget_color_detect = QWidget()
instance.widget_color_detect.setGeometry(200, 200, 500, 200)
instance.widget_color_detect.setWindowTitle('颜色检测')
# 创建一个按钮,该按钮的父对象为instance.widget_color_detect
# 当该按钮被点击时执行信号发射函数
instance.button_widget_color_detect = QPushButton("执行", instance.widget_color_detect)
instance.button_widget_color_detect.setGeometry(30, 70, 50, 50)
instance.button_widget_color_detect.clicked.connect(instance.signal_color_detect_emit)
# 创建一个action,当该action被触发时运行show_color_detect
action_color_detect_widget_show = QAction('&颜色检测', instance)
action_color_detect_widget_show.triggered.connect(instance.show_color_detect_widget)