Mahsa
Mahsa

Reputation: 1550

Best value for threshold in Canny

I have an image which I want to detect edges on that. I found Canny has been used a lot ( I don't know whether I have a better option than that). I have set the values as follow:

  Imgproc.Canny(img, img, 10, 100, 3,true)

I've changed threshold values but don't see that much of a change in my image. Can anyone explain to me if there is a logical way to figure out numbers for threshold values (my image is gray scale)

Thank you...

Upvotes: 19

Views: 54470

Answers (3)

Abdulelah Alkesaiberi
Abdulelah Alkesaiberi

Reputation: 31

You can use this equation it is useful and you can apply bluer to enhance it.

blurred_img = cv2.blur(img,ksize=(5,5))
med_val = np.median(img) 
lower = int(max(0 ,0.7*median_pix))
upper = int(min(255,1.3*median_pix))
edges = cv2.Canny(image=img, threshold1=lower,threshold2=upper)

Upvotes: 3

Matthew Thomas
Matthew Thomas

Reputation: 855

As Samer said it could be case by case. Here is some code that uses trackbars in opencv, and displays the canny image next to the original, in order to quickly experiment with different threshold values.

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

def callback(x):
    print(x)

img = cv2.imread('your_image.png', 0) #read image as grayscale


canny = cv2.Canny(img, 85, 255) 

cv2.namedWindow('image') # make a window with name 'image'
cv2.createTrackbar('L', 'image', 0, 255, callback) #lower threshold trackbar for window 'image
cv2.createTrackbar('U', 'image', 0, 255, callback) #upper threshold trackbar for window 'image

while(1):
    numpy_horizontal_concat = np.concatenate((img, canny), axis=1) # to display image side by side
    cv2.imshow('image', numpy_horizontal_concat)
    k = cv2.waitKey(1) & 0xFF
    if k == 27: #escape key
        break
    l = cv2.getTrackbarPos('L', 'image')
    u = cv2.getTrackbarPos('U', 'image')

    canny = cv2.Canny(img, l, u)

cv2.destroyAllWindows()

Upvotes: 5

Samer
Samer

Reputation: 1980

I think this should be taken case by case, if you post some sample images would be useful, but I will try to answer anyways. Here is from Opencv Documents

Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );
where the arguments are:

detected_edges: Source image, grayscale
detected_edges: Output of the detector (can be the same as the input)
lowThreshold: The value entered by the user moving the Trackbar
highThreshold: Set in the program as three times the lower threshold (following Canny’s recommendation)
kernel_size: We defined it to be 3 (the size of the Sobel kernel to be used internally)

What usually works for me is highThreshold = 255 and lowThreshold = 255/3

Upvotes: 12

Related Questions