MATLAB: How to find the angle in an image like this

image processing

1.png

Best Answer

What I would do is to first call bwareaopen() to remove small noise. Then scan down row by row to get the left and right columns. Then average them together to get an average midline. Then pass the midline coordinates into polyfit() to get a line fit through them. Here's a start
[rows, columns, numberOfColorChannels] = size(mask)
mask = bwareaopen(mask, 20);
midlines = nan(rows, 1);
for row = 1 : rows
col1 = find(mask(row, :), 1, 'first')
col2 = find(mask(row, :), 1, 'last')
% Ignore lines with too many white pixels
if sum(mask(row, col1:col2)) > 5
continue;
end
midlines(row) = (col1+col2) / 2;
end
x = 1 : rows;
coefficients = polyfit(x, midlines, 1);
theFit = polyval(coefficients, x);
hold on;
plot(theFit, x, 'r-', 'LineWidth', 2);
Now you'll still need to figure out which rows have good data and which need to be thrown out before you call polyfit(). Then you'll have to find the bottom and compute the angle.
See if you can finish it.