图片
我试图找到图像中矩形的位置。以图像的顶部为引用,如何找到矩形的位置?我想要四个顶点的坐标。
我尝试过 findContours 和有界矩形方法,但无法获得坐标。帮助将不胜感激。
最佳答案
只需获取轮廓,然后找到边界矩形。查看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)
结果:
关于python - Python对象的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51940070/