Hough Transform not working to recognize a line I have an image composed of small white dots that should stay on the same line.



I wanted to recognize this line using the Hough Transform. To do that I binarized the image, calculated the centroid of each dot and therefore I got an image that is all black except a few white pixels in the position of the centroids of the original dots.



Then I applied the hough transform algorithm (already implemented in Matlab), but it looks not capable to fully detect this line. In particular it skips the last dot in the bottom.



Do you know why this is happening? I would like to understand why the hough trasform method is not working properly and if there is any kind of improvement I can apply.

Here is my Matlab code:

BW = imbinarize(data,0.04);

s = regionprops(BW,'centroid');
centroids = cat(1, s.Centroid);
imshow(BW)
hold on
plot(centroids(:,1),centroids(:,2), 'r*')
BW(:,:)=0;
for k=1:size(centroids,1)
    BW(round(centroids(k,2)),round(centroids(k,1)))=1;
end

[H,T,R] = hough(BW,'RhoResolution',0.1,'Theta',-90:1:89.9);
P  = houghpeaks(H,5,'Theta',T,'threshold',ceil(0.3*max(H(:))));
lines = houghlines(BW,T,R,P,'FillGap',10000,'MinLength',1);
figure, imshow(BW), hold on
max_len = 0;
for k = 1:length(lines)
xy = [lines(k).point1; lines(k).point2];
plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green'); 

plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');
plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');

len = norm(lines(k).point1 - lines(k).point2);
if ( len &gt; max_len)
   max_len = len;
   xy_long = xy;
end
end
plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','cyan');
What you want is just to find the function 

$$y(x) = mx + q$$

that fits through the centroids you've found.

You wouldn't do a Hough transform on that (since Hough transforms generally perform badly in presence of only few representatives of the full line, and are pretty computationally intense), but simply look for something like the least squared error fit of a $y(x)$ through the $(x_i, y_i)$ tuples given by the coordinates of your centroids.