轮廓拟合直线python代码
以下是一个轮廓拟合直线的Python代码示例:
import cv2
# 读取图像
img = cv2.imread('image.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_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
# 拟合直线
rows, cols = img.shape[:2]
for cnt in contours:
if len(cnt) > 30:
[vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)
lefty = int((-x * vy / vx) + y)
righty = int(((cols - x) * vy / vx) + y)
cv2.line(img, (cols - 1, righty), (0, lefty), (0, 255, 0), 2)
# 显示结果图像
cv2.imshow('Contours', img)
cv2.waitKey(0)
这段代码首先读取一个图像,然后将其转换为灰度图像,并进行二值化处理。接着,使用OpenCV的findContours函数查找图像中的轮廓,并将其绘制出来。最后,使用fitLine函数对每个轮廓进行直线拟合,并将拟合的直线绘制在图像上
原文地址: https://www.cveoy.top/t/topic/e8eg 著作权归作者所有。请勿转载和采集!