My script can detect horizonal and vertical lines but I can’t figure out why it fails on diagonal lines. As an example I’m creating simple black and white images of letters with this code:
###### CODE TO CREATE THE IMAGES from PIL import Image, ImageDraw, ImageFont import numpy as np import cv2 as cv from matplotlib import pyplot as plt def create_image(size, bgColor, message, font, fontColor): W, H = size image = Image.new('1', size, bgColor) draw = ImageDraw.Draw(image) _, _, w, h = draw.textbbox((0, 13), message, font=font) draw.text(((W - w) / 2, (H - h) / 2), message, font=font, fill=fontColor) return image myMessage = 'l' myFont = ImageFont.truetype("data/arial.ttf", 1714) myImage = create_image((5142, 2000), 'white', myMessage, myFont, 'black') myImage.save('hello_world.png', "PNG") Image.open("hello_world.png").show() img = cv.imread("hello_world.png")
And here is the code to detect the straight lines in the image:
def findStraightLines(img, rho, theta, threshold, min_line_length, max_line_gap): gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) kernel_size = 5 blur_gray = cv.GaussianBlur(gray, (kernel_size, kernel_size), 0) low_threshold = 50 high_threshold = 150 edges = cv.Canny(blur_gray, low_threshold, high_threshold) line_image = np.copy(img) * 0 # creating a blank to draw lines on # Run Hough on edge detected image # Output "lines" is an array containing endpoints of detected line segments lines = cv.HoughLinesP(edges, rho, theta, threshold, np.array(), min_line_length, max_line_gap) if lines != None: for line in lines: for x1, y1, x2, y2 in line: cv.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 5) # Draw the lines on the image lines_edges = cv.addWeighted(img, 0.8, line_image, 1, 0) else: lines_edges = img.copy() return lines_edges, lines
And here I run the functions and plot the images with the straight lines that are detected outlined in red:
lines_edges, lines = findStraightLines(img, rho=1, theta=np.pi / 180, threshold=20, min_line_length=50, max_line_gap=0) plt.imshow(lines_edges)
f you run this minimally reproducible example you will see that with a lower case
l as an image, the code detects all of the straight edges, and with a lower case
o there are no straight edges detected. This is what I hoped to see. However with a lower case
w the code is only detecting the horizontal aspects, and is missing the diagonal lines.
How can I adjust this to make it detect diagonal lines at different orientations, as well as horizonal and vertical lines? Thanks in advance!