Angle of lines in binary image

4 views (last 30 days)
Jan Kubicek
Jan Kubicek on 6 Jun 2021
Commented: Matt J on 7 Jun 2021
Dear colleagues,
I would like to kindly ask you about computing angles in binary image. I have this binary image (and many similar), containing three binary objects. I need to fit such binary (white) objects with lines, and mainly compute angles of this lines to each object would be represented by one angle.
I tried to do that by I was not successful. I just know that MATLAB contains the inbuilt function polyfit(), which should be the way to approximate such binary objects but I cannot implement that. I would need to store these angles in some variable. For instance, when I have such binary image with three binary objects, this variable such contain three angles.
Thank you very much for the help.
  1 Comment
Matt J
Matt J on 7 Jun 2021
I just know that MATLAB contains the inbuilt function polyfit(), which should be the way to approximate such binary objects
polyfit may fail if the best fit line is perfectly vertical, or nearly so.

Sign in to comment.

Answers (2)

Matt J
Matt J on 6 Jun 2021
Edited: Matt J on 6 Jun 2021
It may be helpful to use linear2dFit from this FIle Exchange package
load Image
hold on;
for i=1:numel(S)
hold off
Angles=-[lfit.angle], %line angles in degrees
Angles =
38.2326 43.5104 55.4355

Image Analyst
Image Analyst on 6 Jun 2021
Try polyfit like this:
% Read in image (the posted image is RGB).
binaryImage = imread('image.png');
% Convert from color image to logical
if size(binaryImage, 3) > 1
binaryImage = binaryImage(:,:,1) > 0;
imshow(binaryImage); % Display image.
axis('on', 'image'); % Display axis tick marks
% Identify separate connected components. (Could also use bwlabel)
props = regionprops(binaryImage, 'PixelList');
for k = 1 : length(props) % For each blob...
% Get coordinates of the points in the blob.
x = props(k).PixelList(:, 1);
y = props(k).PixelList(:, 2);
% Fit a line
coefficients = polyfit(x, y, 1);
% Get endpoints of the line
x1 = min(x);
y1 = polyval(coefficients, x1);
x2 = max(x);
y2 = polyval(coefficients, x2);
hold on;
% Draw line from left most x to rightmost x.
line([x1,x2], [y1,y2], 'Color', 'r', 'LineWidth', 3);
% Compute angle with origin at (1,1) which is the upper left corner of the image, as usual.
angle(k) = atan2d(y2-y1, x2-x1);
% In case you wanted it from the other corner, the lower left corner.
angle2(k) = atan2d(y1-y2, x2-x1);
% Report angles to command window.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!