user14342237
user14342237

Reputation: 48

Probabilistic Hough lines returning only angled lines

I'm attempting to parse floorplans to turn them into an array of line coordinates using HoughLinesP in opencv-python and the function is only returning lines that are angled and have no relation to the actual lines in my image.

Here is my code:

import cv2

# Read image and convert to grayscale
img = cv2.imread('C:/Data/images/floorplan/extremely basic.png', -1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Get lines with probabilistic hough lines
found_lines = cv2.HoughLinesP(gray, 1, 3.14 / 160, 100,
                              minLineLength=1, maxLineGap=10)

# Loop through found lines and draw each line on original image
for line in found_lines:
    x1, y1, x2, y2 = line[0]
    cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 1)

# Show image, wait until keypress, close windows.
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

And here is what's going to be returned with threshold 150 and 100 respectively:

enter image description here

enter image description here

Original

I've tried tinkering with all options and attempted non-probabilistic Hough lines to no avail.

Upvotes: 1

Views: 189

Answers (1)

B200011011
B200011011

Reputation: 4258

The problem was with image inversion and parameters. You have to do further adjustments as this does not give all lines.

The code is test on google colab. Remove from google.colab.patches import cv2_imshow and replace cv_imshow with cv2.imshow for local usage.

Partial Image Ouput

enter image description here

Code

import cv2
import numpy as np
from google.colab.patches import cv2_imshow

# Read image and convert to grayscale
img = cv2.imread('1.jpg', 0)
#gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


s1, s2 = img.shape
new_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)


# Get lines with probabilistic hough lines
found_lines = cv2.HoughLinesP(erosion, np.pi/180, np.pi/180, 10, minLineLength=4, maxLineGap=4)

# Loop through found lines and draw each line on original image
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)

# Show image, wait until keypress, close windows.
print("ORIGINAL IMAGE:")
cv2_imshow(img)
#cv2.imshow('image', img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()

Upvotes: 1

Related Questions