Search code examples
matlabimage-processingsignal-processingmatlab-figure

How can I measure the length of line segments in image mask in MATLAB?


I have a binary image (BW_roi.mat), displayed below. And I wanted to measure the length of every line segment.
image mask

I tried the solution given in this link hough-transform. But it does not work out for me. It just measured the length of some lines as shown below.

Hough method not working

I tried the other code

clc; clear all; close all;
load BW_ROI.mat

boundaries = bwboundaries(BW_roi_nodot);
patchno=1  %Let select patch 1
b = boundaries{patchno}; % Extract N by 2 matrix of (x,y) locations.
x = b(:, 1);
y = b(:, 2);

It though gives me points (x,y) that make up these polygons. But how can I get the line segment length of specific patch?


Solution

  • I'd propose using convexhull in combination with the algorithm here to reduce the number of vertices in the detected polygons. Seems to work pretty well. I'll leave it to you to use the adjacency matrix produced by bwboundaries to throw away duplicates.

    load BW_ROI.mat
    
    [B,L,N,A] = bwboundaries(BW_roi_nodot);
    
    for k = 1:N
      boundary = fliplr(B{k});
      
      % take a convex hull of the bounded polygon
      idxn = convhull(boundary, 'Simplify', true);
      
      % use this algorithm to further simplify the polygon
      % https://ww2.mathworks.cn/matlabcentral/fileexchange/41986-ramer-douglas-peucker-algorithm
      point_reduced = DouglasPeucker(boundary(idxn,:), 5);
      
      % make the shape, get the side lengths
      shp = polyshape(point_reduced);
      vertex_deltas = diff([shp.Vertices; shp.Vertices(1,:)], 1);
      edge_lengths = sqrt(sum(vertex_deltas.^2, 2));
      
      % plot animation
      imshow(BW_roi_nodot), hold on
      plot(shp), drawnow, pause(0.5)
    end