I am trying to get a Linear best fit line through certain points in an image but am unable to get a line that would seem logical. I am not sure if I am doing something wrong here, or if that really is the best fit line in this case.
This is the original image:
This is the result after selecting an area of interest, filtering the edge, and then plotting the best fit line through the pixels of that edge.
I expected the best fit line (blue line in the results) to be almost vertical. However, as shown in the image, it is tilted at an angle while the red points are all close to a vertical and not scattered around the image. How can I correctly detect the vertical line?
Code:
image = imread('https://i.stack.imgur.com/rQ1SQ.png');
image = rgb2gray(image(85:270, 165:210, :));
filter = [ones(1, 6);zeros(1,6);-ones(1,6)];
filter = filter.';
filtered =imfilter(image,filter);
regions = regionprops(bwlabel(filtered,8), 'Area', 'PixelList');
[maxarea, maxindex] = max([regions.Area]);
p = polyfit(regions(maxindex).PixelList(:,1), regions(maxindex).PixelList(:,2), 1);
x = 1:size(image,2);
y = polyval(p,x);
subplot(1,3,1), imshow(image, 'border','tight');
hold on;
plot(x,y,'b');
title('Area of Interest in Original Image')
subplot(1,3,2), imshow(filtered);
hold on;
plot(x,y,'b');
title('Vertical Edge after Filtering')
subplot(1,3,3), imshow(fim);
hold on;
plot(x,y,'b');
plot(regions(maxindex).PixelList(:,1), regions(maxindex).PixelList(:,2), 'r.');
title('Image with points plotted')
Code Reference: Shai's answer on a related question.