查找轮廓的坐标

mar*_*zuk 2 python opencv

我试图找到给定矩形每个角的坐标。到目前为止,我已经能够使用轮廓函数获得两个角,但是当我查看整个轮廓数组时,有很多点需要筛选。我只是在寻找最极端的值(最大和最小 x 和 y 值)

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()
Run Code Online (Sandbox Code Playgroud)

我筛选了contours返回给我的内容及其大量的点,这些点似乎是我图像对角线上的所有点。有什么方法可以简化我接收的点,在这种情况下是这个矩形/平行四边形的角?

测试轮廓

ilk*_*444 6

findContours函数返回轮廓上的像素。您可以尝试approxPolyDP使用 OpenCV 的函数来找到轮廓的多边形近似值。用法和解释可以在这里找到。在您的情况下,它将类似于以下内容:

epsilon = cv2.arcLength(contours[0],True)
approx = cv2.approxPolyDP(contours[0],epsilon,True)
Run Code Online (Sandbox Code Playgroud)