How to optimize Canny threshold for edge determination and imfill for a bounded object in greyscale image?

26 次查看(过去 30 天)
I am using the edge function to identify the boundaries of objects within a 2D greyscale image. I also wish to fill in the bounded edge region. I found it somewhat effective to first convert my greyscale image into a binary image with an upper greyscale value (i.e. cut-off values above), then use the edge function. However, I do not know how to optimize the canny threshold values. I attached my code below and an example image. I need to process several hundred images with varying intensity ranges (greyscale values), so my goal is to have a scalar or some input to the canny threshold based on intensity of each individual image.
I apologize for the clunky coding. I am a novice.
intthreshold = 208;
cannythreshold = [0.1 0.2];
minpixelarea = 100;
binarythreshimg=image1(:,:)<intthreshold; % This is the initial cut-off intensity to eliminate some of the background pixels
image1b=edge(binarythreshimg,'canny',[(cannythreshold)]); % find the edge of the material within the remaining pixels
[boundrows,boundcols]=find(image1b==1);
boundaries=[boundcols,boundrows];
BW_filled = imfill(image1b,'holes');
boundaries = bwboundaries(BW_filled);
row = cellfun(@(x) size(x,1),boundaries);
boundaries = boundaries(row>minpixelarea); % Only use the boundaries that are larger than minpixelarea
[~,I] = sort(cellfun('length', boundaries)); % Sort the boundaries smallest to largest
boundaries = boundaries(I);
bigboundary = boundaries(end); % I assumed the largest boundary is the region I want to select
%% Plot the edge boundary on top of the image %%
figure()
imshow(image1)
hold on
plot(bigboundary{1}(:,2),bigboundary{1}(:,1))

回答(1 个)

Rohit
Rohit 2023-3-24
One of the approaches to optimize the Canny threshold values for each individual image is to use "Otsu's method", which automatically calculates the threshold based on the intensity distribution of the image.
The “graythresh” function in MATLAB calculates the Otsu threshold for the image, which is then used to set the Canny threshold values. The following is a basic example which you can experiment with based on your requirements like number of edges to be detected, thresholding criterion etc.
% Calculate Otsu threshold
level = graythresh(image1);
% Set Canny threshold based on Otsu threshold
cannythreshold = [level/2 level];
% Apply Canny edge detection
image1b = edge(binarythreshimg,'canny',cannythreshold);
You can refer to following documentation link to know more about this function:- https://www.mathworks.com/help/images/ref/graythresh.html

产品


版本

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by