对象的坐标Python

2024-04-27 13:37:18 发布

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

图像

我试图在图像中找到矩形的位置。考虑到图像的顶部作为参考,如何找到矩形的位置?我要四个顶点的坐标。在

我尝试过findContours和有界矩形方法,但都没能得到坐标。如有帮助,不胜感激。在


Tags: 方法图像矩形顶点findcontours
2条回答

只要得到轮廓,然后找到边界矩形。检查官方文件中的this tutorial。在

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)

矩形左上、右下点坐标((x1,y1),(x2,y2)):

^{pr2}$

结果:

res.jpg

只要调整cv2 tutorial,就可以找到最大的轮廓,然后得到它的边界矩形。在

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 

我看到的这个图像

^{pr2}$

相关问题 更多 >