我尝试使用opencv-python中的HoughLinesP解析平面图,将其转换为一组线坐标,但函数仅返回倾斜的线,且这些线与图像中的实际线条无关。
这是我的代码:
import cv2# 读取图像并转换为灰度图img = cv2.imread('C:/Data/images/floorplan/extremely basic.png', -1)gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 使用概率霍夫线检测获取线条found_lines = cv2.HoughLinesP(gray, 1, 3.14 / 160, 100, minLineLength=1, maxLineGap=10)# 遍历找到的线条,并在原始图像上绘制每条线for line in found_lines: x1, y1, x2, y2 = line[0] cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 1)# 显示图像,等待按键,关闭窗口。cv2.imshow('image', img)cv2.waitKey(0)cv2.destroyAllWindows()
以下是分别使用阈值150和100时的返回结果:
我尝试调整了所有选项,并尝试了非概率霍夫线检测,但都没有成功。
回答:
问题出在图像反转和参数设置上。你需要进一步调整,因为这并不能检测到所有线条。
代码在Google Colab上测试过。删除from google.colab.patches import cv2_imshow
,并将cv_imshow
替换为cv2.imshow
以便在本地使用。
部分图像输出
代码
import cv2import numpy as npfrom google.colab.patches import cv2_imshow# 读取图像并转换为灰度图img = cv2.imread('1.jpg', 0)#gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)s1, s2 = img.shapenew_img = np.zeros([s1,s2],dtype=np.uint8)new_img.fill(255)ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)cv2_imshow(thresh1)kernel = np.ones((3,3),np.uint8)erosion = cv2.erode(thresh1,kernel,iterations = 1)cv2_imshow(erosion)# 使用概率霍夫线检测获取线条found_lines = cv2.HoughLinesP(erosion, np.pi/180, np.pi/180, 10, minLineLength=4, maxLineGap=4)# 遍历找到的线条,并在原始图像上绘制每条线for line in found_lines: x1, y1, x2, y2 = line[0] cv2.line(new_img, (x1, y1), (x2, y2), (0, 0, 255), 1) cv2_imshow(new_img) #cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 1)# 显示图像,等待按键,关闭窗口。print("原始图像:")cv2_imshow(img)#cv2.imshow('image', img)#cv2.waitKey(0)#cv2.destroyAllWindows()