程序:
# -*-coding:utf-8 -*-
import cv2 as cv2
import numpy as np
# 标准霍夫变换
img = cv2.imread('new.png')
# img = cv2.imread('new1.png')
# img = cv2.imread('new2.png')
house = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 获取灰度图
edges = cv2.Canny(house, 50, 200)
lines = cv2.HoughLines(edges, 1, np.pi/180, 260) # 霍夫变换返回的就是极坐标系中的两个参数 rho和theta
print(np.shape(lines))
lines = lines[:, 0, :] # 将数据转换到二维
for rho, theta in lines:
a = np.cos(theta)
b = np.sin(theta)
# 从图b中可以看出x0 = rho x cos(theta)
# y0 = rho x 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), 1)
cv2.imshow('img', img)
cv2.imshow('edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果:

如果图像中没有直线,则上面的程序会执行失败,所以如果有图片中不存在直线的情况,程序在实际跑的时候,需要做异常处理.

该博客介绍了如何利用Python的OpenCV库执行霍夫变换来检测图像中的直线。程序首先读取图像并转为灰度图,然后应用Canny边缘检测。通过霍夫变换找到可能的直线,并在原始图像上绘制这些直线。当图像中不存在直线时,程序需进行异常处理以避免错误。
1万+

被折叠的 条评论
为什么被折叠?



