python opencv尝试使用矩方法找到轮廓中心

问题描述

这是我的代码

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()

函数markCenter查找轮廓及其中心。

函数设法找到实际上可以标记中心的位置,但是当我尝试找到中心像素的值时,我从另一个像素得到了错误的答案/答案。

1

那是为什么,我该如何解决

解决方法

Numpy 使用行/列(又名 y/x)与使用 x/y 的 OpenCV。打印时使用的是numpy,所以print(img[cX,cY])需要变成print(img[cY,cX])

可以在这里找到这种常见混淆的一个很好的例子: https://stackoverflow.com/a/56849032/848419