对象Python的坐标

时间:2018-08-21 00:26:44

标签: python image numpy opencv

图片

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

我尝试过findContours和有界矩形方法,但无法获取坐标。帮助将不胜感激。

2 个答案:

答案 0 :(得分: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))的左上和右下点的坐标:

(369, 0) (901, 433)

结果:

res.jpg

答案 1 :(得分:1)

仅需调整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 

我得到的这张图片

>>> corners 

array([[371,   1],
   [900,   1],
   [900, 430],
   [371, 430]])