Reputation: 25
Image
I am trying to find the position of the rectangle in the image. Considering the top part of the image as reference, how can I find the position of the rectangle? I want the coordinates of the four vertices.
I have tried findContours and bounded rectangle method but have not been able to get the coordinates. Help would be appreciated.
Upvotes: 0
Views: 3116
Reputation: 2726
just adapting the cv2 tutorial, you can find the largest contour and then obtain its bounding rectangle.
img = cv2.imread('/home/kvnp/Desktop/v02J6.jpg',0) #read in the image with correct dtype
_,thresh = cv2.threshold(img,200,255,0) # threshold the image
_,contours,_ = cv2.findContours(thresh, 1, 2) # find the contours
cnt = sorted(contours, key = lambda c: -len(c))[0] # order from largest to smallest and select the largest
x,y,w,h = cv2.boundingRect(cnt) # make bounding rectangle around the largest contour
corners = np.array([[x,y],[x+w,y],[x+w,y+h],[x,y+h]]) # make array of corners sorted clockwise
This image I get
>>> corners
array([[371, 1],
[900, 1],
[900, 430],
[371, 430]])
Upvotes: 1
Reputation: 2427
Just get contour and then find bounding rectangle. Check this tutorial from official documentation.
import cv2
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(thresh,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_NONE)
x1, y1, w, h = cv2.boundingRect(contours[0])
x2, y2 = x1 + w, y1 + h
print((x1, y1), (x2, y2))
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.imwrite('res.jpg', img)
Coordinates of upper-left and lower-right points of rectangle ((x1, y1), (x2, y2)):
(369, 0) (901, 433)
Result:
Upvotes: 2