Python3制作鼠标拾色器并显示十六进制数值(有单独窗口显示取色)
代码如下,结合OpenCV的鼠标事件,窗体大小的调整,我们可以轻松地制作拾色器并进行显示:
- import cv2
-
- import numpy as np
-
- def onmouse_pick_points(event, x, y, flag,img):
- img_bg = np.zeros((100,100), dtype=np.uint8)
- img_bg = cv2.cvtColor(img_bg, cv2.COLOR_GRAY2BGR)
- if event == cv2.EVENT_LBUTTONDOWN:
- print(img.shape)
- #x = x - 51 #坐标矫正
- #y = y - 44
- x,y = y,x
- print('x = %d, y = %d' % (x, y))
- print('b = %d, g = %d ,r = %d' % (img[x,y,0], img[x,y,1],img[x,y,2]))
- print(rgb2hex(img[x,y]))
- img_bg[:,:,0]=img[x,y,0]
- img_bg[:,:,1]=img[x,y,1]
- img_bg[:,:,2]=img[x,y,2]
- cv2.imshow('background',img_bg)
- cv2.waitKey(0)
-
- def rgb2hex(RGB):
- text = '#' + ''.join([hex(i)[-2:].replace('x', '0') for i in list(map(int, RGB))])
- return text
-
- img = cv2.imread("G:\\videos\\mofang.jpeg")
-
- #img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
-
- WIN_NAME = 'pick_points'
- cv2.namedWindow(WIN_NAME,cv2.WINDOW_AUTOSIZE)
- cv2.setMouseCallback(WIN_NAME, onmouse_pick_points, img)
- cv2.resizeWindow("pick_points",img.shape[1],img.shape[0])
- while True:
- cv2.imshow(WIN_NAME, img)
- key = cv2.waitKey(30)
- if key == 27: # ESC
- break
- cv2.destroyAllWindows()
效果如下:
如有疑问请留言———————————————————————————————》》》》