Python CV2 未检测到明显的线条

问题描述 投票:0回答:1

Here's the image

我是计算机视觉新手。目标是检测晶格中几乎垂直的黑线并将它们旋转到垂直。我应用了霍夫线变换。然而它并没有看到明显的黑线。

这是代码。我做错了什么?

lines = cv2.HoughLinesP(binary_image, 50, np.pi/180, threshold=50, minLineLength=100, maxLineGap=500)

image_with_lines = binary_image.copy()
for line in lines:
    x1, y1, x2, y2 = line[0]
    angle_rad = np.arctan2(y2 - y1, x2 - x1)  
    angle_deg = np.degrees(angle_rad)
    
    if 88 <= angle_deg <= 92:  
        cv2.line(image_with_lines, (x1, y1), (x2, y2), (0,0,255), 5) 

谢谢!

python opencv hough-transform
1个回答
0
投票

这是一个解决方案。我做了以下步骤

  1. 阈值并反转二值图像。
  2. 扩大图像以创建接近完整直线的连续点。可以使用“DILATE_PARAMETER”来调整膨胀。
  3. 调整了 cv2.HoughLinesP 参数
import cv2
import numpy as np
#Parameter to control dilation to create a continuous line.
DILATE_PARAMETER = 2

original_image = cv2.imread('input_image.jpg')
binary_image = cv2.imread('input_image.jpg',0)
binary_image[binary_image<127] =0
binary_image[binary_image>=127] =255

#Inverting the image.
binary_image = cv2.bitwise_not(binary_image)

kernel = np.ones((3,3), np.uint8)
binary_image = cv2.dilate(binary_image, kernel, iterations = 2)
for _ in range(DILATE_PARAMETER-1):
        binary_image = cv2.dilate(binary_image, kernel, iterations = 2)
    
#print(np.unique(binary_image))
#print(binary_image.shape)

#Can check the images after inverting and dilation
cv2.imwrite('binary_image.jpg',binary_image)

lines = cv2.HoughLinesP(binary_image, 1, np.pi/180, threshold=150, minLineLength=400, maxLineGap=20)
for line in lines:    
    x1, y1, x2, y2 = line[0]
    angle_rad = np.arctan2(y2 - y1, x2 - x1)  
    angle_deg = np.degrees(angle_rad)
    
    if 80 <= angle_deg <= 100:  
        print("Found Line : ", line[0], " in angle :", angle_deg)        
        cv2.line(original_image, (x1, y1), (x2, y2), 255, 5)

cv2.imwrite('image_with_lines.jpg',original_image)

输出

Found Line :  [580   1 608 526]  in angle : 86.94711748520757
Found Line :  [600  34 608 514]  in angle : 89.04515874612783
Found Line :  [597  35 606 526]  in angle : 88.94988945946136
Found Line :  [270  93 277 516]  in angle : 89.0519294294594
Found Line :  [581  36 606 510]  in angle : 86.98086815086273

© www.soinside.com 2019 - 2024. All rights reserved.