interactiveColorDetect.py 2.6 KB

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