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.
Why is that, and how can I fix it?