darkman9333
darkman9333

Reputation: 131

Find coordinates of contours

I'm trying to find the coordinates of each corner of a given rectangle. So far I've been able to obtain two corners using the contours function, but when I look through the whole contour array there is an abundance of points to sift through. I'm only looking for the most extreme values (max and min x- and y-values)

import cv2
import numpy as np

#open image
img = cv2.imread('cnt-coords.jpg')

#convert to black and white
bw = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#threshold image
ret, thresh = cv2.threshold(bw,127,255,0)

#find contours
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

#obtain the first 2 points of contours
cntx1 = contours[0][0]
cntx = contours[0][1]

#convert coords to points
pt1 = (cntx1[0][0],cntx1[0][1])
pt2 = (cntx[0][0],cntx[0][1])

#draw circles on coordinates
cv2.circle(img,pt1,5,(0,255,0),-1)
cv2.circle(img,pt2, 5, (0,255,0),-1)

#display the image
cv2.imshow('f',img)

cv2.waitKey(0)
cv2.destroyAllWindows()

I sifted through what contours returns to me and its a huge array of points, which seems to be all the points along the diagonal of my image. Is there any way to simplify which points I'm receiving, in this case the corners of this rectangle/parallelogram?

test contours

Upvotes: 2

Views: 17096

Answers (1)

ilke444
ilke444

Reputation: 2741

findContours function returns pixels on the contour. You can try approxPolyDP function of OpenCV to find a polygonal approximation to the contour. The usage and explanation can be found here. In your case it would be something like the following:

epsilon = cv2.arcLength(contours[0],True)
approx = cv2.approxPolyDP(contours[0],epsilon,True)

Upvotes: 6

Related Questions