canny edge detection, hough transform and find 10 peaks in matlab in matlab

Canny Edge Detection

The Canny edge detection algorithm is a popular edge detection technique. It is available in the edge function in MATLAB. Here is an example of how to apply the Canny edge detection algorithm to an image:

main.m
% Read in image
img = imread('example_image.jpg');

% Convert to grayscale
gray_img = rgb2gray(img);

% Apply Canny edge detection with default parameters
edge_img = edge(gray_img, 'canny');

% Show the original image and the edge image side by side
figure;
imshowpair(img, edge_img, 'montage');
296 chars
13 lines

Hough Transform

The Hough transform is a technique used to detect lines and curves in an image. It is available in the hough function in MATLAB. Here is an example of how to apply the Hough transform to an image:

main.m
% Read in image
img = imread('example_image.jpg');

% Convert to grayscale
gray_img = rgb2gray(img);

% Apply Canny edge detection to get binary edge image
edge_img = edge(gray_img, 'canny');

% Apply Hough transform to detect lines
[H,theta,rho] = hough(edge_img);

% Show the Hough transform matrix
figure;
imshow(imadjust(mat2gray(H)),[],'XData',theta,'YData',rho,'InitialMagnification','fit');
xlabel('\theta (degrees)'), ylabel('\rho');
axis on, axis normal, hold on;
colormap(gca,hot);

% Find peaks in Hough transform matrix
peaks = houghpeaks(H, 10);
x = theta(peaks(:,2));
y = rho(peaks(:,1));

% Overlay detected lines on original image
figure;
imshow(img), hold on
plot(x,y,'s','color','white');
707 chars
29 lines

Peak Finding

To find the peaks in the Hough transform matrix, you can use the houghpeaks function. Here is an example of how to use the houghpeaks function:

main.m
% Read in image
img = imread('example_image.jpg');

% Convert to grayscale
gray_img = rgb2gray(img);

% Apply Canny edge detection to get binary edge image
edge_img = edge(gray_img, 'canny');

% Apply Hough transform to detect lines
[H,theta,rho] = hough(edge_img);

% Find peaks in Hough transform matrix
peaks = houghpeaks(H, 10);
disp(peaks);
346 chars
16 lines

The houghpeaks function returns a matrix where each row is the (x,y) coordinates of a peak in the Hough transform matrix. In this example, we are finding the top 10 peaks.

gistlibby LogSnag