下面是一个使用OpenCV多边形逼近的Python代码示例:
import cv2
import numpy as np
# 读取图像
img = cv2.imread('curve.png')
# 将图像转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用Canny边缘检测算法检测图像边缘
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# 使用霍夫线变换检测直线
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=100, maxLineGap=10)
# 循环遍历每条直线
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
# 使用多边形逼近函数拟合图像轮廓
approx = cv2.approxPolyDP(edges, 0.01 * cv2.arcLength(edges, True), True)
# 在图像中绘制多边形
cv2.drawContours(img, [approx], 0, (0, 0, 255), 2)
# 显示图像
cv2.imshow('Result', img)
cv2.waitKey(0)