如何将cv2.findContours生成的离散的轮廓点连接成线
时间: 2023-10-14 07:16:24 浏览: 48
要将cv2.findContours生成的离散的轮廓点连接成线,可以使用cv2.approxPolyDP函数。该函数可以将离散的轮廓点近似为一组更少的点,这些点可以表示为更平滑的曲线。下面是一个示例代码:
```python
import cv2
image = cv2.imread("contours.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制原始轮廓
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
# 连接轮廓点成线
for cnt in contours:
epsilon = 0.01 * cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
cv2.drawContours(image, [approx], -1, (0, 0, 255), 3)
cv2.imshow("Contours", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个例子中,我们首先使用cv2.findContours函数找到图像中的轮廓。然后我们使用cv2.approxPolyDP函数将每个轮廓点近似为一条线。最后,我们使用cv2.drawContours函数将原始轮廓和连接后的轮廓绘制在图像上,以便比较它们的不同之处。