Har*_*ong 4 python opencv roi image-processing computer-vision
我的目标是确定某个点是否位于ROI内。我设法裁剪了ROI,并可以像这样访问其宽度和高度
width = roi.shape[0] #total rows as width
height = roi.shape[1] #total columns as height
Run Code Online (Sandbox Code Playgroud)
但是,我缺少2个其他变量,即顶部和左侧坐标,以便构造以下语句来确定我的点是否存在于ROI中。
if(top < point_x < top + width and left < point_x < left + height)
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助和时间,谢谢。
You can use cv2.pointPolygonTest() to determine if your point exists inside a ROI.
Essentially you can check if a point is within a contour. The function returns +1, -1, or 0 to indicate if a point is inside, outside, or on the contour, respectively. Since you already have the ROI coordinates, you can use that as the contour to detect if the point is inside the ROI. Here's an example that finds the circle contour then checks if two points are within the contour.
Test image

Image after finding contour and checking points

Results
point1 -1.0
point2 1.0
Therefore point1 is outside the contour and point2 is inside the contour.
import cv2
import numpy as np
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(gray, 120, 255, 1)
cnts = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
point1 = (50, 50)
cv2.circle(image, point1, 8, (100, 100, 255), -1)
cv2.putText(image, 'point1', (point1[0] -10, point1[1] -20), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), lineType=cv2.LINE_AA)
point2 = (150, 150)
cv2.circle(image, point2, 8, (200, 100, 55), -1)
cv2.putText(image, 'point2', (point2[0] -10, point2[1] -20), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), lineType=cv2.LINE_AA)
for c in cnts:
cv2.drawContours(image, [c], -1, (36, 255, 12), 2)
res1 = cv2.pointPolygonTest(c, point1, False)
res2 = cv2.pointPolygonTest(c, point2, False)
print('point1', res1)
print('point2', res2)
cv2.imshow('image', image)
cv2.imwrite('image.png', image)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |