4

My objective is to determine whether a point resides within a ROI or not. I have managed to crop an ROI and can access its width and height like this

width = roi.shape[0] #total rows as width
height = roi.shape[1] #total columns as height

However, I lack 2 additional variables, which are top and left coordinates in order to construct the following statement to determine whether my point exists within ROI or not.

if(top < point_x < top + width and left < point_x < left + height)

Appreciate your help and time, thank you.

coffeewin
  • 182
  • 3
  • 6
  • 26
Harrison Chong
  • 150
  • 3
  • 11

1 Answers1

7

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()
nathancy
  • 42,661
  • 14
  • 115
  • 137