Was that Imperial Red, Lust, or Crimson? ...I am pretty sure it was just red.

In which we find the H, S, and V values for an image's pixels.

Recently I have been working on an application that requires me to locate a small colored dot in an image or video frame.  In order to accomplish this, I have been using OpenCV.  For reasons outside the scope of this post, I am working with the images/frames in the HSV color space.  You can find more information about HSV in general and OpenCV's HSV implementation here [1].  There you will also find a nifty tool - ColorWheelHSV - to help you visualize OpenCV's HSV implementation.  However, if you are like me, you might find it difficult to determine proper H, S, and V values by eyeballing your target and the output of ColorWheelHSV.

Enter HSVpixelpicker.

The Python script below will allow you to determine the H, S, and V values of a given pixel in an image as OpenCV sees it.  Simply pass the image file name with -f on the command line, click on the pixel you are interested in, and the H, S, and V values will be printed to the console.  Using this tool, you can check the exact value of the pixel or pixels you are interested in.  The more samples you have to test, the better the idea you will get of the H, S, and V values you are dealing with.  You can then refer to ColorWheelHSV to select your ranges.

The code is copyright © 2013 Matthew Witherwax and released under the BSD license.

from optparse import OptionParser
import cv2
from cv2 import cv

class HSVpixelpicker:
    def __init__(self):
        # original image
        self.image = None
        # image converted to HSV
        self.imageHSV = None
        
        # create window to show image
        cv2.namedWindow('image')
        # wire click handler
        cv.SetMouseCallback('image',self.on_mouse, 0);
        
    # handles left clicking on the image
    # gets the pixel under the cursor and prints its HSV values
    def on_mouse(self, event,x,y,flag,param):
      if(event==cv.CV_EVENT_LBUTTONDOWN):
        pixel = self.imageHSV[y][x]
        print 'H:',pixel[0],'\tS:',pixel[1],'\tV:',pixel[2]
        
    def open_image(self, filename):
        self.image = cv2.imread(filename)
        self.imageHSV = cv2.cvtColor(self.image,cv2.COLOR_BGR2HSV)
        
    def show(self, filename):
        self.open_image(filename)
        while True:
            cv2.imshow('image', self.image)
            
            # show image until user presses the esc key
            if cv.WaitKey(10) == 27:
                break
            
        # clean up
        cv2.destroyAllWindows()

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option('-f', '--file', action='store',
        type='string', dest='filename')
    (options, args) = parser.parse_args()

    hsv_picker = HSVpixelpicker()
    hsv_picker.show(options.filename)

[1] http://www.shervinemami.info/colorConversion.html

HSVpixelpicker.py (3.03 kb)

Loading