I'm trying to get the pixel coordinates of a specific roi in a image. I created the roi using mask. The code and the result is shown below.
import cv2
import numpy as np
img = cv2.imread("Inxee.jpg")
img = cv2.resize(img, (640, 480))
mask = np.zeros(img.shape, np.uint8)
points = np.array([[273,167], [363, 167], [573, 353], [63, 353]]) ##taking random points for ROI.
cv2.fillPoly(mask, [points], (100, 0, 100))
img = cv2.addWeighted(img, 0.7, mask, 0.5, 0)
values = img[np.where((mask == (100, 0, 100)).all(axis=1))]
print(values)
##cv2.imshow("mask", mask)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
so in the image we can see the ROI.
I tried to use the
values = img[np.where((mask == (100, 0, 100)).all(axis=1))]
but here I'm getting only values not coordinates. So is there any way to get those coordinates?
CodePudding user response:
To get the coordinates, you could do it like this:
pixels_in_roi = [(i_x,i_y) for i_x, col in enumerate(mask) for i_y, val in enumerate(col) if val == (100,0,100)]
There are faster ways to do it.
I'm not sure what your goal is in the end, but it sounds like undistorting this area as if it was a top-down view could be the next step. In that case this might help you: https://pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/
Edit: Here is a better solution using np.where: https://stackoverflow.com/a/27175491/7438122 The input 'mask' has to be a numpy array then (which it should already be in your case), not a list.
Christoph is right though: If you tell us what you want to achieve, there might be a way without extracting the indices at all.
CodePudding user response:
Thanks for the solutions and possibilities friends, I just did,
val = np.where(mask == (100, 0, 100))
coordinate = list(zip(val[0], val[1]))
print(coordinate)
with this i got the coordinates! Thanks!