Leah Fernández
Leah Fernández

Reputation: 41

Skimage: trying to find a straight line with Hough_Line

This is my first ever python-project and I am a little stuck. I am trying to detect a straight horizontal line in an image. The image is a black and white picture of a drop on a surface and I want to get the line where the drop meets the surface. I use cv2.Canny to detect the outlines of the drop which works just fine. Now trying to use the edges-image with a Hough transformation to find a straight line and print it onto the original image.I don't know if it does find a line but I can't manage to print it or if no lines a detected. Printing a line in generell works.

I am hoping to get some tipps on what I need to change or what I could try to make it work.

I am using Spyder with/in Anaconda and Python 3.10.

Thank you!

This is the Code so far:

import numpy as np
import cv2
from skimage.transform import hough_line, probabilistic_hough_line

def fit_baseline(image):
    # Convert the image to grayscale
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imshow('Graubild', gray_image)

    # Apply edge detection
    edges = cv2.Canny(gray_image, 80, 120, apertureSize=3)
    cv2.imshow('Ecken',edges)

    # Perform the Hough Transform
    h, theta, d = hough_line(edges)
    print('h:', h)
    print('theta: ', theta)
    print('d: ', d)

    # Find the most prominent line (baseline)
    angle, dist = np.unravel_index(np.argmax(h), h.shape)
    angle = np.rad2deg(theta[angle])
    dist = d[dist]

    # Convert from polar to slope-intercept form
    if angle != 0:
        slope = -1 / np.tan(np.deg2rad(angle))
        intercept = dist / np.sin(np.deg2rad(angle))
    else:
        slope = float('inf')
        intercept = dist

    return slope, intercept

# Load the image
image = cv2.imread('Bilder/drop_zoomed.png')


# Fit the baseline
slope, intercept = fit_baseline(image)

# Draw the baseline on the image
height, width, _ = image.shape
baseline_start_x = 0
baseline_start_y = int(intercept)
baseline_end_x = width - 1
baseline_end_y =  int(slope * baseline_end_x + intercept)
baseline_color = (0, 255, 0)  # Green color (BGR format)
baseline_thickness = 2
image_with_baseline = cv2.line(image, (baseline_start_x, baseline_start_y), (baseline_end_x, baseline_end_y),
                               baseline_color, baseline_thickness)

# Display the image with the baseline
cv2.imshow('Image with Baseline', image_with_baseline)
cv2.waitKey(0)
cv2.destroyAllWindows()


This is the kind of picture I am trying to detect the horizontal line:

enter image description here

This is the result I am hoping to get:

enter image description here

Upvotes: 1

Views: 292

Answers (0)

Related Questions