canny边缘检测算法matlab代码
时间: 2023-05-25 10:06:51 浏览: 270
以下是canny边缘检测算法的MATLAB代码示例:
```
%% Canny Edge Detection Algorithm
% Step 1: Apply Gaussian filter to smooth the image in order to remove noise.
% Step 2: Find the intensity gradients of the image.
% Step 3: Apply non-maximum suppression to get rid of spurious responses to edge detection.
% Step 4: Apply double threshold to determine potential edges.
% Step 5: Track edge by hysteresis: Finalize the detection of edges by suppressing all the other edges that are weak and not connected to strong edges.
% Load image
I = imread('example.jpg');
% Convert to grayscale
I_gray = rgb2gray(I);
% Smooth the image using a Gaussian filter
G = fspecial('gaussian', [5 5], 1);
I_smooth = imfilter(I_gray, G, 'same');
% Compute the gradients using Sobel operators
Gx = [-1 0 1; -2 0 2; -1 0 1];
Gy = [-1 -2 -1; 0 0 0; 1 2 1];
Ix = conv2(I_smooth, Gx, 'same');
Iy = conv2(I_smooth, Gy, 'same');
grad_mag = sqrt(Ix.^2 + Iy.^2);
grad_dir = atan2(Iy, Ix);
% Non-max suppression
for i = 1:size(grad_mag,1)
for j = 1:size(grad_mag,2)
theta = grad_dir(i,j);
if theta < 0
theta = theta + pi;
end
% Find the appropriate indices for interpolation
row_above = ceil(i - sin(theta));
row_below = floor(i + sin(theta));
col_left = ceil(j - cos(theta));
col_right = floor(j + cos(theta));
if row_above > 0 && row_below <= size(grad_mag,1) && col_left > 0 && col_right <= size(grad_mag,2)
interp_vals = [grad_mag(row_above,j) grad_mag(row_below,j); grad_mag(i,col_left) grad_mag(i,col_right)];
interp_weights = [(i-row_below)*cos(theta) + (j-col_right)*sin(theta); (i-row_above)*cos(theta) + (j-col_left)*sin(theta)];
if grad_mag(i,j) < sum(interp_vals(:) .* interp_weights(:))
grad_mag(i,j) = 0;
end
end
end
end
% Double thresholding
T_high = 0.2 * max(grad_mag(:));
T_low = 0.1 * max(grad_mag(:));
grad_mag_thresh = zeros(size(grad_mag));
grad_mag_thresh(grad_mag >= T_high) = 1;
grad_mag_thresh(grad_mag >= T_low & grad_mag < T_high) = 0.5;
% Hysteresis
[row,col] = find(grad_mag_thresh == 0.5);
for i = 1:length(row)
if any(grad_mag_thresh(row(i)-1:row(i)+1,col(i)-1:col(i)+1) == 1)
grad_mag_thresh(row(i),col(i)) = 1;
end
end
grad_mag_thresh(grad_mag_thresh ~= 1) = 0;
% Display the results
figure;
subplot(121);
imshow(I_gray);
title('Original Image');
subplot(122);
imshow(grad_mag_thresh);
title('Canny Edge Detection');
```