cv2.approxPolyDP 示例
时间: 2023-08-13 09:43:33 浏览: 97
下面是一个使用cv2.approxPolyDP函数的简单示例:
假设我们有一个图像中的轮廓,如下图所示:

我们想将该轮廓近似为一个较简单的形状,可以使用cv2.approxPolyDP函数。
代码示例:
```python
import cv2
# 读取图像并转换为灰度图像
img = cv2.imread('contour.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 轮廓近似处理
epsilon = 0.01 * cv2.arcLength(contours[0], True)
approx = cv2.approxPolyDP(contours[0], epsilon, True)
# 绘制轮廓和近似形状
cv2.drawContours(img, [contours[0]], -1, (0, 255, 0), 3)
cv2.drawContours(img, [approx], -1, (0, 0, 255), 3)
# 显示结果
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
运行结果:

其中,红色线条表示近似后的形状,绿色线条表示原始轮廓。
阅读全文
相关推荐


















