Python 对象的坐标

Python 对象的坐标,python,image,numpy,opencv,Python,Image,Numpy,Opencv,形象 我试图找到矩形在图像中的位置。将图像的顶部作为参考,如何找到矩形的位置?我想要四个顶点的坐标 我尝试过FindContentours和bounded rectangle方法,但无法获得坐标。非常感谢您的帮助。只需获取轮廓,然后找到边界矩形即可。查阅官方文件 import cv2 img = cv2.imread('image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gr

形象

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


我尝试过FindContentours和bounded rectangle方法,但无法获得坐标。非常感谢您的帮助。

只需获取轮廓,然后找到边界矩形即可。查阅官方文件

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))的左上和右下点坐标:

结果:


只需获得轮廓,然后找到边界矩形。查阅官方文件

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))的左上和右下点坐标:

结果:

只需调整,即可找到最大轮廓,然后获得其边界矩形

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]])
只需调整,您可以找到最大的轮廓,然后获得其边界矩形

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]])