求等高线坐标

2024-04-23 20:00:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到给定矩形每个角的坐标。 到目前为止,我已经能够使用轮廓函数获得两个角,但是当我查看整个轮廓数组时,有大量的点要筛选。我只寻找最极端的值(最大值和最小值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()

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

test contours


Tags: toimageimportconvertimgthreshold数组coords
1条回答
网友
1楼 · 发布于 2024-04-23 20:00:33

findContours函数返回轮廓上的像素。您可以尝试OpenCV的approxPolyDP函数来找到轮廓的多边形近似值。用法和解释见here。在您的情况下,可能是以下情况:

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

相关问题 更多 >