1

This is my code.

import cv2

#detect all centers of objects
#mark all centers
#return modified image

def markCenter(canny,img):

    #get contours using cv2 method - "findContours"
    contours,hierarchy = cv2.findContours(canny,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)

    #sort contour by area
    contours = sorted(contours, key=lambda x: cv2.contourArea(x))
    contours = sorted(contours, key=cv2.contourArea,reverse=True)

    #iterate over contour list
    for cnt in contours:

        #get center of contour using cv2 method - "moments"
        M = cv2.moments(cnt)

        #parse returned data from "moments"
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])

        # draw the  center of the shape on the image

        print(cX,cY)  #print coordinates

        print(img[cX,cY])  #print value of pixel in center of contour

        cv2.circle(img, (cX, cY), 1, (255, 255, 255), -1)  #mark the center of the contour
    return img #return modified image


def main():

    #read image
    img = cv2.imread("resources/result_shapedet.jpg")

    #show image
    cv2.imshow("original",img)

    #convert image to greyscale
    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    #blurr image
    imgBlur = cv2.GaussianBlur(imgGray, (7, 7), 1)

    #detect edges of objects with canny method
    imgCanny = cv2.Canny(imgBlur, 40, 40)

    #show image with marked centers
    cv2.imshow("centers",markCenter(imgCanny,img))

    #never close image windows
    cv2.waitKey(0)

if __name__=="__main__":
    main()

The function markCenter finds the contours and their center.

The function manages to find can in fact mark the centers, but when I try to find the value of the pixel in the center, I get the wrong answer/answer from another pixel.

1

Why is that, and how can I fix it?

seshadri_c
  • 6,906
  • 2
  • 10
  • 24

1 Answers1

2

Numpy uses rows/cols (AKA y/x) vs OpenCV which uses x/y. When you do the print, you are using numpy, so print(img[cX,cY]) needs to become print(img[cY,cX])

A good example of this common confusion can be found here: https://stackoverflow.com/a/56849032/848419

Also remember that OpenCV uses BGR, so if you're using RGB as the reference values to identify the color, you need to reverse the elements.

img_RGB = img[::-1]
VoteCoffee
  • 4,692
  • 1
  • 41
  • 44