I would like to click on an object and get the pixel coordinates which are the color that I picked before.
I found this code on the internet
import cv
tolerancia = 30
def evento_mouse(event,x,y,flags,param):
if event==cv.CV_EVENT_LBUTTONDOWN:
pixel=cv.Get2D(imagen,y,x)
print 'X =',x,' Y =',y
print 'R =',pixel[2],'G =',pixel[1],'B =',pixel[0]
cv.InRangeS(imagen,(pixel[0]-tolerancia,pixel[1]-tolerancia,pixel[2]- tolerancia),(pixel[0]+tolerancia,pixel[1]+tolerancia,pixel[2]+tolerancia),temporal)
cv.ShowImage('Color',temporal)
c = cv.Get2D(temporal,y,x)
print c[0],c[1],c[2] # I always get: 255, 0, 0
imagen=cv.LoadImage('prueba2.png')
cv.ShowImage('Prueba',imagen)
temporal=cv.CreateImage(cv.GetSize(imagen),cv.IPL_DEPTH_8U,1)
cv.SetMouseCallback('Prueba',evento_mouse)
cv.WaitKey(0)
I am trying to see if the pixel is white or black. but I always get the same value: 255, 0, 0 (blue = 255)
There are a couple of things you need to understand.
You are using old ‘cv’ interface of OpenCV. In that case, to get a pixel value, you use the function ‘cv2.Get2D’ which returns you a tuple of corresponding BGR values.
1. Why blue color, ie (255,0,0) for binary images ?
For both color images and grayscale/binary images, same tuple of 3 elements is returned, but for grayscale images, first element is the pixel value, remaining two are irrelevant, so they are zeros. So you get values like (255,0,0) etc since you are reading pixel values of binary image(temporal).
2. Why always (255,0,0) ?
When you click on the original image, a corresponding binary image is created, where the region corresponding to color you clicked become white and all other region become black. If you clicked on a RED color in original image, your binary image will be such that, all red region will be white and remaining black. So obviously, the pixel you clicked is always WHITE. So if you read that pixel from binary image, you get only (255,0,0) always.
I would like to recommend you to migrate to OpenCV new Python interface, ‘cv2’ module. It has a lot of advantages. Main advantage is the Numpy support which is a big deal. You can check this SOF for some comparison : What is different between all these OpenCV Python interfaces?
You can also get some startup tutorials on cv2 from here : http://www.opencvpython.blogspot.com