如何将矩形转换为轮廓

时间:2019-02-08 16:52:26

标签: python opencv

使用OpenCV,我们可以从轮廓生成矩形(list)

[x, y, w, h] = cv2.boundingRect(contour)

其中xy是点的坐标,wh是各自的宽度和高度。

有没有一种方法可以将这些矩形转换回轮廓?

1 个答案:

答案 0 :(得分:0)

轮廓只是点的列表。因此,只需将x, y, w, h的值转换为点,并将其存储在列表中,这就是您的轮廓。

因此,您的点将为(x, y), (x+w, y), (x, y+h), (x+w), (y+h),轮廓将为[(x, y), (x+w, y), (x, y+h), (x+w), (y+h)]

说明:

我应该更详细一些。使用此代码将您的点转换为轮廓。

import cv2
import numpy as np

x = 10
y = 20
width = 50
height = 60

img = np.zeros((100,100,1), np.uint8)

p1 = np.matrix([[x, y]])
p2 = np.matrix([[x + width, y]])
p3 = np.matrix([[x, y + height]])
p4 = np.matrix([[x + width, y + height]])

contour = list(np.array([[p1, p2, p3, p4]]))

cv2.drawContours(img, contour, -1, 255)

cv2.imshow("image", img)
if cv2.waitKey() == 27:
    cv2.destroyAllWindows()

输出:

enter image description here

相关问题