以下是使用Python和OpenCV库实现直线检测的代码示例:

import cv2
import numpy as np

# 读取图像
img = cv2.imread('lines.jpg')

# 将图像转为灰度
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 进行边缘检测
edges = cv2.Canny(gray, 50, 150, apertureSize=3)

# 进行霍夫直线变换
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)

# 绘制检测到的直线
for line in lines:
    rho, theta = line[0]
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a * rho
    y0 = b * rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))
    cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)

# 显示图像
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

在这个示例中,我们首先读取了一张图像并将其转为灰度图像。然后使用Canny边缘检测算法检测图像的边缘。接下来,使用霍夫直线变换检测图像中的直线。最后,将检测到的直线绘制在原始图像上并显示出来。

用Python写一段直线检测的代码

原文地址: https://www.cveoy.top/t/topic/bwKx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录