OpenCV python 霍夫曼直线检测
处理图片:[computer.jpg]
import cv2
import matplotlib.pyplot as plt
import numpy as np
def main():
# 1.导入图片
img_src = cv2.imread("computer.jpg")
img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
# 2.执行canny
img_edges = cv2.Canny(img_gray, 30, 110, apertureSize=3)
img_rgb = cv2.cvtColor(img_src, cv2.COLOR_BGR2RGB)
img_show = img_rgb.copy()
# 3.霍夫曼直线检测
lines = cv2.HoughLines(img_edges, 1, np.pi / 180, 140)
# 4.显示直线
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_rgb, (x1, y1), (x2, y2), (0, 0, 255), 2)
# 5.显示图片
plt.subplot(121)
plt.imshow(img_rgb, cmap="gray")
plt.axis("off")
plt.subplot(122)
plt.imshow(img_show)
plt.axis("off")
plt.show()
if __name__ == '__main__':
main()
处理结果: