I need to do a least squares fit on an image
3 views (last 30 days)
Show older comments
I need to run a code that does the least squares fit on an image. I was asked to find the equation of any line in the image using this method. Once I load the image how do I proceed?
4 Comments
Image Analyst
on 19 Apr 2022
OK, can you post your image? It sounds like they want you to do it, not us, so if you need help, post your hough code and we can fix it.
Answers (1)
Pratyush Swain
on 14 Sep 2023
Hey Jessica,
I understand you want to find the equation for hough line in an image through least squares method.
Please refer to the following code example where I have demonstrated how to leverage least square fit method to find hough lines equation using the provided image:
image = imread('image.jpeg'); % Loading testing image
grayImage = rgb2gray(image);
% Perform Edge Detection
edgeImage = edge(grayImage, 'Canny');
% Apply Hough Transform
[H, theta, rho] = hough(edgeImage);
% Extract Line Parameters
numPeaks = 10; % Number of peaks to detect
peaks = houghpeaks(H, numPeaks);
lines = houghlines(edgeImage, theta, rho, peaks);
% Fit Lines using Least Squares
lineEquations = cell(numPeaks, 1);
for k = 1:numPeaks
xy = [lines(k).point1; lines(k).point2];
disp(xy)
x = xy(:, 1);
y = xy(:, 2);
p = polyfit(x, y, 1); % Perform least squares fitting
slope = p(1);
intercept = p(2);
lineEquations{k} = sprintf('y = %.2fx + %.2f', slope, intercept);
end
% Display the Image with Detected Lines
figure;
imshow(image);
hold on;
for k = 1:numPeaks
xy = [lines(k).point1; lines(k).point2];
plot(xy(:, 1), xy(:, 2), 'LineWidth', 2, 'Color', 'r');
text(xy(1, 1), xy(1, 2), lineEquations{k}, 'Color', 'g', 'FontSize', 8);
end
hold off;
% Show Line Equations
disp('Line Equations:');
for k = 1:numPeaks
disp(lineEquations{k})
end

For more information, please refer to these links.
Hope this helps.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
