I'm working with the OpenCV library in Python and trying to detect the long and short edges of a rectangular shape in an image. I have used the Canny edge detector and then applied the Hough transform to detect the lines. However, I am encountering an issue where the output is detecting multiple lines of the same length, and it is not drawing the 'y' edge correctly.
Here is a simplified version of my code:
import cv2
import numpy as np
img = cv2.imread(r"C:\Users\Asus Hn004W\Desktop\1.jpeg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 78, 106, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
for r_theta in lines:
arr = np.array(r_theta[0], dtype=np.float64)
r, theta = arr
a = np.cos(theta)
b = np.sin(theta)
x0 = a*r
y0 = b*r
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.imshow('', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
I would like to understand why multiple lines of the same length are being detected and why the 'y' edge is not being drawn correctly. What modifications should I make to the code to accurately detect and draw the edges of the rectangular shape?
Thank you in advance for any assistance.enter image description here
multiple lines
All results with votes above the threshold will be returned from HoughLines()
.
So, you should employ some post-process to decide your result from them. Process called "Non maximum suppression" is often employed.
not drawing the 'y' edge correctly
Perhaps, your threshold (200
) is too large for vertical lines (or canny result is not good).