pythonopencvimage-processing

How to detect edges of the following image


I am trying to detect the fringes/edges of the following image but it doesn't work

Here is the python code:nevermind the title

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Load the image
image_path = 'your path to image'
image = cv2.imread(image_path)

# Convert to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply Gaussian blur to reduce noise
blurred_image = cv2.GaussianBlur(gray_image, (5, 5), 0)

# Apply Canny edge detection
edges = cv2.Canny(blurred_image, threshold1=50, threshold2=150)

edges_colored = np.zeros_like(image)
edges_colored[:, :, 1] = edges  # Set the red channel

overlay = cv2.addWeighted(image, 0.8, edges_colored, 1, 0)

# Display the overlaid image
plt.figure(figsize=(8, 6))
plt.imshow(cv2.cvtColor(overlay, cv2.COLOR_BGR2RGB))
plt.title('Original Image with Detected Edges in Red')
plt.axis('off')
plt.show()

And this is the image I want to detect edges for should follow the lines for the fringes. I have tried almost everything black and white increasing the contrast but it doesn't work. I have modified other image manually and for that it work and I don't know what can be the reason here is the working example: enter image description here

What am I doing wrong that it doesn't work for the new image but for some reason works for the other. I have tried normalizing and played with threshold and brightness and contrast but didn't help. Thanks for the help!!


Solution

  • Try doing a color threshold with cv2.inRange() with lower=(170,0,0) and upper=(255,255,255) (instead of doing BGR2Gray and thresholding). Then convert to 8-bit gray (multiply by 255, then convert to uint8 using astype(np.uint8)). Then invert. Then do your Canny. Adjust the lower blue threshold value as desired to get more or less gap.

    I did this quickly in ImageMagick, but can convert this to Python/OpenCV, if you have trouble.

    magick image.png -alpha off -color-threshold "rgb(0,0,170)-rgb(255,255,255)" -negate -canny 0x1+10%+30% x.png
    

    enter image description here

    Is this close to what you want?