recurf
recurf

Reputation: 235

open cv, img[x,y] always returning 0

I get centroid of objects in an image like this:

gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    _, contours, _ = cv2.findContours(gray.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_L1)

    centres = []
    for i in range(len(contours)):
        moments = cv2.moments(contours[i])
        centres.append((int(moments['m10']/moments['m00']), int(moments['m01']/moments['m00'])))

I am looping over the centres and trying to get the colour of each centre pixel. For some reason every return is 0,0,0

for c in centres:
    print img[c]

I also get this error

IndexError: index 484 is out of bounds for axis 0 with size 480

Upvotes: 0

Views: 81

Answers (1)

marcoresk
marcoresk

Reputation: 1955

Image into openCv numpy structure is a 3D matrix. To have the intensity in the pixel of coordinates x,y (remember that y are the rows) you have to do this (in grayscale image)

intensity = img[y,x]

And when I read your error line I think it is your unique mistake.

To have colours (in BGR) you have to write something like

blue = img[y,x,0]
green = img[y,x,1]
red = img[y,x,2]

You should check if it is your situation by using

print c

and see what are the center coordinates. If you obtain something lixe

c(x,y) = 484, 300

in a 640 x 480 image, it is sure that you have to use img[y,x] because coordinates gives x first but matrices want rows first.

value = img[row,column]

Upvotes: 1

Related Questions