Path: blob/master/ColorSpaces/interactiveColorDetect.py
3118 views
import cv2,argparse,glob1import numpy as np23# mouse callback function4def showPixelValue(event,x,y,flags,param):5global img, combinedResult, placeholder67if event == cv2.EVENT_MOUSEMOVE:8# get the value of pixel from the location of mouse in (x,y)9bgr = img[y,x]1011# Convert the BGR pixel into other colro formats12ycb = cv2.cvtColor(np.uint8([[bgr]]),cv2.COLOR_BGR2YCrCb)[0][0]13lab = cv2.cvtColor(np.uint8([[bgr]]),cv2.COLOR_BGR2Lab)[0][0]14hsv = cv2.cvtColor(np.uint8([[bgr]]),cv2.COLOR_BGR2HSV)[0][0]1516# Create an empty placeholder for displaying the values17placeholder = np.zeros((img.shape[0],400,3),dtype=np.uint8)1819# fill the placeholder with the values of color spaces20cv2.putText(placeholder, "BGR {}".format(bgr), (20, 70), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)21cv2.putText(placeholder, "HSV {}".format(hsv), (20, 140), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)22cv2.putText(placeholder, "YCrCb {}".format(ycb), (20, 210), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)23cv2.putText(placeholder, "LAB {}".format(lab), (20, 280), cv2.FONT_HERSHEY_COMPLEX, .9, (255,255,255), 1, cv2.LINE_AA)2425# Combine the two results to show side by side in a single image26combinedResult = np.hstack([img,placeholder])2728cv2.imshow('PRESS P for Previous, N for Next Image',combinedResult)293031if __name__ == '__main__' :3233# load the image and setup the mouse callback function34global img35files = glob.glob('images/rub*.jpg')36files.sort()37img = cv2.imread(files[0])38img = cv2.resize(img,(400,400))39cv2.imshow('PRESS P for Previous, N for Next Image',img)4041# Create an empty window42cv2.namedWindow('PRESS P for Previous, N for Next Image')43# Create a callback function for any event on the mouse44cv2.setMouseCallback('PRESS P for Previous, N for Next Image',showPixelValue)45i = 046while(1):47k = cv2.waitKey(1) & 0xFF48# check next image in the folder49if k == ord('n'):50i += 151img = cv2.imread(files[i%len(files)])52img = cv2.resize(img,(400,400))53cv2.imshow('PRESS P for Previous, N for Next Image',img)5455# check previous image in folder56elif k == ord('p'):57i -= 158img = cv2.imread(files[i%len(files)])59img = cv2.resize(img,(400,400))60cv2.imshow('PRESS P for Previous, N for Next Image',img)6162elif k == 27:63cv2.destroyAllWindows()64break6566