Reputation: 277
I am trying to draw a shape and then check whether the point is inside the shape or no. Thought using cv2.polylines()
to draw it and cv2.pointPolygonTest()
to test should work am getting an error which is not very informative.
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'
I am guessing the shape created with cv2.polylines()
is not a contour. What would be the correct way to do it then? My current code:
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()
Upvotes: 0
Views: 12636
Reputation: 4561
polylines
is not the right input, it is used to draw a shape (docs)
pointPolygonTest
instead needs the contour as an input (docs)
dist = cv2.pointPolygonTest(pts, (52,288), False)
will return 1.0
, meaning inside the contour.
Note that you can perform a pointPolygonTest without an image. But if you want to draw the results, you can use this code as a starter:
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()
Result:
Upvotes: 6