I'm attempting to use hough transform to find the lines that I need. I'm working with multiple images and an example of one is this
https://i.stack.imgur.com/KmGdP.jpg
However when using the hough transform the result comes out as
https://i.stack.imgur.com/DJvbg.jpg
I don't know why only one line ends up on the sign in which I want the hough lines to encompass all four sides, and with the other images I have some don't even have hough lines showing up on them. What am i doing wrong? Is there any corrections to be put in place? This is the code I'm running
import numpy as np
import cv2 as cv
import os
images = []
edges = []
light_range = (0, 0, 0)
dark_range = (80, 80, 80)
#Importing testing images
for i in os.listdir("Directional Signage/Train"):
img = cv.imread(os.path.join("Directional Signage/Train", i))
if img is None:
print("Couldn't read this image" str(i))
else:
images.append(img)
for i in range(0, len(images)):
#Preprocessing
#mask = cv.inRange(images[i], light_range, dark_range)
img = np.float32(images[i]) / 255.0
gx = cv.Sobel(img, cv.CV_32F, 1, 0, ksize=1)
gy = cv.Sobel(img, cv.CV_32F, 0, 1, ksize=1)
mag, angle = cv.cartToPolar(gx, gy, angleInDegrees=True)
gray = cv.cvtColor(mag,cv.COLOR_BGR2GRAY)
gray = np.uint8(gray * 255.0)
edges = cv.Canny(gray,50,150,apertureSize = 3)
lines = cv.HoughLines(edges,2,np.pi/90,200)
#edges.append(lines)
for rho,theta in lines[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))
cv.line(images[i],(x1,y1),(x2,y2),(0,0,255),2)
for i in range(0, len(images)):
cv.imshow("blobby " str(i), images[i])
l = cv.waitKey(0)
CodePudding user response:
You're just iterating over one line (lines[0]
), so it is obvious that you get one line from each image, do this instead:
[...]
for line in lines:
for rho,theta in line:
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))
cv.line(images[i],(x1,y1),(x2,y2),(0,0,255),2)
[...]
Update: now rather than getting a single red line my entire image goes red
The reason is that, the Hough
function finds every lines but by priority. The lines which are more likely to be a real line are at first part of the list.
First two lines of the list, maybe is what you're looking for, so try this:
[...]
for line in lines[:2]:
for rho,theta in line:
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))
cv.line(images[i],(x1,y1),(x2,y2),(0,0,255),2)
[...]