我正在尝试绘制形状,然后检查该点是否在形状内。想到使用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'
我猜测用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()
答案 0 :(得分:0)
polylines
不是正确的输入,它用于绘制形状(docs)
pointPolygonTest
相反需要轮廓作为输入(docs)
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()
结果: