使用 cv2.pointPolygonTest() 和 cv2.polylines() 时出现问题

Mud*_*yla 0 python opencv

我正在尝试绘制一个形状,然后检查该点是否在形状内部。认为使用cv2.polylines()绘制它并cv2.pointPolygonTest()测试应该可以工作,但出现了一个信息量不大的错误。

Traceback (most recent call last):
  File "C:\Users\XXX\Desktop\Heatmap\cvtest.py", line 32, in <module>
    dist = cv2.pointPolygonTest(cv2.polylines(img,[pts],True,(0, 255 , 0), 2), (52,288), False)
cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\geometry.cpp:103: error: (-215:Assertion failed) total >= 0 && (depth == CV_32S || depth == CV_32F) in function 'cv::pointPolygonTest'
Run Code Online (Sandbox Code Playgroud)

我猜用创建的形状cv2.polylines()不是轮廓。那么正确的做法是什么?我当前的代码:

import cv2
import numpy as np

img = cv2.imread('image.png')

pts = np.array([[18,306],[50,268],[79,294],[165,328],[253,294],[281,268],[313,306],[281,334],[270,341],[251,351],[230,360],[200,368],[165,371],[130,368],[100,360],[79,351],[50,334],[35,323]], np.int32)
pts = pts.reshape((-1,1,2))

dist = cv2.pointPolygonTest(cv2.polylines(img,[pts],True,(0, 255 , 0), 2), (52,288), False)
#print(dist)

cv2.imshow('test', img)
cv2.waitKey()
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

J.D*_*.D. 5

polylines不是正确的输入,它用于绘制形状(文档
pointPolygonTest,而是需要轮廓作为输入(文档

dist = cv2.pointPolygonTest(pts, (52,288), False)将返回1.0,表示在轮廓内部。

请注意,您可以在没有图像的情况下执行 pointPolygonTest。但如果您想绘制结果,可以使用以下代码作为入门:

    import cv2
    import numpy as np

    #create background
    img = np.zeros((400,400),dtype=np.uint8)
    # define shape
    pts = np.array([[18,306],[50,268],[79,294],[165,328],[253,294],[281,268],[313,306],[281,334],[270,341],[251,351],[230,360],[200,368],[165,371],[130,368],[100,360],[79,351],[50,334],[35,323]], np.int32)
    pts = pts.reshape((-1,1,2))
    # draw shape
    cv2.polylines(img,[pts],True,(255), 2)
    # draw point of interest
    cv2.circle(img,(52,288),1,(127),3)
    # perform pointPolygonTest
    dist = cv2.pointPolygonTest(pts, (52,288), False)
    print(dist)
    # show image
    cv2.imshow('test', img)
    cv2.waitKey()
    cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述