Hough Demo
>> %% Hough Demo
>>
>> %% Load image, convert to grayscale and apply Canny operator to find edge pixels
>> Img = imread(‘shapes.png’);
>> Grays = rgb2grah(img);
>> Edges = edge(grays, ‘canny’);
>>
>> Figure, imshow(img), title(‘Original image’);
>> Figure, imshow(grays), title(‘Grayscale’);
>> Figure, imshow(edges), title(Edge pixels’);
>>
>> %% Apply Hough transform to find candidate lines
>> [accum theta rho] = hough(edges);
>> %%accum = accumulator array
>> %% thetha = vector of theta values or angles
>> %% rho = vector of radius values or rho
>> figure, imagesc(accum, ‘Xdata’, theta, ‘Ydata’, rho), title(‘Hough accumulator’);
>>
>> %% find peaks in the Hough accumulator matrix
>> peaks = houghpeaks(accum, 100); %% 100 maximum number of peaks we are interested in
>> hold on; plot(theta(peaks(:, 2)), rho(peaks(:, 1)), ‘rs’); hold off;
>>
>> size(peaks)
Ans = 13 2 %% 13 peaks were found
>> %% Find lines (segments) in the image
>> line_segs = houghlines(edges, theta, rho, peaks);
>> line_segs
Line_segs =
1x28 struct array with fileds: %% 28 segments were found
Point1
Point2
Theta
Rho
>> %% plot the line segments
>> figure, imshow(img), title(‘Line segments’);
>> hod on;
>> for k = 1: length(line_segs)
>> endpoints = [line_segs(k).point1; line_segs(k).point2];
>> plot(endpoints(:, 1), endpoints(:, 2), ‘LineWidth’, 2, ‘Color’, ‘green’);
>> end
>> hold off;
>>
>> %% Alt.: More precise lines
>> peaks = houghpeaks(accum, 100, ‘Threshold’, ceil(0.6 * max(accum(:))), ‘NHoodSize’, [5 5]);
%% 0.6 times the maximum value in the accumulator array(0.5 default)
%% NHoodSize, size of neighborhood is defined in rho and theta dimensions.A neighborhood size of five degrees along the theta dimension means that a strong line will suppress other lines that are similar but slightly off in direction.
>> size(peaks)
Ans = 7 2 %% 7 peaks were found
>> figure, imagesc(theta, rho, accum), title(‘Hough accumulator’);
>> hold on; plot(theta(peaks(:, 2)), rho(peaks(:, 1)), ‘rs’); hold off;
>>
>> line_segs = houghlines(edges, theta, rho, peaks, ‘FillGap’, 50, ‘MinLength’, 100);
%% increase fillgap to 50 - maximum number of pixels allowed between two segments for them to be counted as one if they lie along the same line.
%% increase the minimum length to be 100 pixels. - for the longer lines
>> figure, imshow(img), title(‘Line segments’);
>> hod on;
>> for k = 1: length(line_segs)
>> endpoints = [line_segs(k).point1; line_segs(k).point2];
>> plot(endpoints(:, 1), endpoints(:, 2), ‘LineWidth’, 2, ‘Color’, ‘green’);
>> end
>> hold off;