Find Specific straight lines in image with Python and CV2

281 Views Asked by At

I Have a specific image: enter image description here

In this picture I try to detect the following lines reliable: enter image description here

I tired to detect them with the following code:

def find_and_draw_lines(img):
    # convert to grayscale
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply Canny edge detection to find edges
    edges = cv2.Canny(img, 50, 150, apertureSize=3)

    
    # Apply Hough Transform to find lines
    lines = cv2.HoughLinesP(edges, rho=1, theta=np.pi/180, threshold=50, minLineLength=30, maxLineGap=10)
    
    img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    print(f"Number of lines found in image: {len(lines)}\n")
    # Draw red lines over the original image
    for line in lines:
        x1, y1, x2, y2 = line[0]
        cv2.line(img, (x1,y1), (x2,y2), (0,0,255), 2)
    
    # Display the image
    cv2.imshow("Image with lines", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

But this code just does not detect the right lines. Most of the lines detected are lines of the ovals(output of the line detection): enter image description here

Is there a way to just detect the marked lines?

More Information on the core Problem onhand:

So I have a Part that should get picked up by a roboter arm. I already managed to locate the part on a workbench, but I still need to know if the Part is orientet face up or face down, to know if I need to turn the part around or not. For this I want to use a webcam and a script of some sort. The script should determine if the part is face up or not.

The big problem is, that the part looks really similar from the top and bottom, so I tried playing around with the angel of the camera to see the differences. With my own eyes I can say confident if the part is face up or not, but with a script it is a bit harder...

I thought this could be done with analyzing the amount of black pixels or with the amount of lines in the image. But so far non have worked.

I could also try to train a custom object detection with yolo or tensorflow, but I think this is a bit overkill...

Here is a image I can provide from the original parts. One is face up and one face down: enter image description here

0

There are 0 best solutions below