Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/ColorSpaces/interactiveColorDetect.py
3118 views
1
import cv2,argparse,glob
2
import numpy as np
3
4
# mouse callback function
5
def showPixelValue(event,x,y,flags,param):
6
global img, combinedResult, placeholder
7
8
if event == cv2.EVENT_MOUSEMOVE:
9
# get the value of pixel from the location of mouse in (x,y)
10
bgr = img[y,x]
11
12
# Convert the BGR pixel into other colro formats
13
ycb = cv2.cvtColor(np.uint8([[bgr]]),cv2.COLOR_BGR2YCrCb)[0][0]
14
lab = cv2.cvtColor(np.uint8([[bgr]]),cv2.COLOR_BGR2Lab)[0][0]
15
hsv = cv2.cvtColor(np.uint8([[bgr]]),cv2.COLOR_BGR2HSV)[0][0]
16
17
# Create an empty placeholder for displaying the values
18
placeholder = np.zeros((img.shape[0],400,3),dtype=np.uint8)
19
20
# fill the placeholder with the values of color spaces
21
cv2.putText(placeholder, "BGR {}".format(bgr), (20, 70), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)
22
cv2.putText(placeholder, "HSV {}".format(hsv), (20, 140), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)
23
cv2.putText(placeholder, "YCrCb {}".format(ycb), (20, 210), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)
24
cv2.putText(placeholder, "LAB {}".format(lab), (20, 280), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)
25
26
# Combine the two results to show side by side in a single image
27
combinedResult = np.hstack([img,placeholder])
28
29
cv2.imshow('PRESS P for Previous, N for Next Image',combinedResult)
30
31
32
if __name__ == '__main__' :
33
34
# load the image and setup the mouse callback function
35
global img
36
files = glob.glob('images/rub*.jpg')
37
files.sort()
38
img = cv2.imread(files[0])
39
img = cv2.resize(img,(400,400))
40
cv2.imshow('PRESS P for Previous, N for Next Image',img)
41
42
# Create an empty window
43
cv2.namedWindow('PRESS P for Previous, N for Next Image')
44
# Create a callback function for any event on the mouse
45
cv2.setMouseCallback('PRESS P for Previous, N for Next Image',showPixelValue)
46
i = 0
47
while(1):
48
k = cv2.waitKey(1) & 0xFF
49
# check next image in the folder
50
if k == ord('n'):
51
i += 1
52
img = cv2.imread(files[i%len(files)])
53
img = cv2.resize(img,(400,400))
54
cv2.imshow('PRESS P for Previous, N for Next Image',img)
55
56
# check previous image in folder
57
elif k == ord('p'):
58
i -= 1
59
img = cv2.imread(files[i%len(files)])
60
img = cv2.resize(img,(400,400))
61
cv2.imshow('PRESS P for Previous, N for Next Image',img)
62
63
elif k == 27:
64
cv2.destroyAllWindows()
65
break
66