create a matlab function that takes a binary image as input and outputs the vertices of the point of each object closest to the center of the image in matlab

main.m
function [vertices] = find_vertices_closest_to_center(bin_image)
% FIND_VERTICES_CLOSEST_TO_CENTER Find the vertices of the object closest to the center.
% Inputs:
%   - bin_image : A binary image
% Outputs:
%   - vertices  : A matrix containing the coordinates of vertices closest to the center of image

% Find the centroid of the binary image
stat = regionprops('table', bin_image, 'Centroid');
centroid = stat.Centroid;

% Compute distance of each object's centroid from the image center
[rows,cols] = size(bin_image);
num_obj = max(max(bwlabel(bin_image)));
distances = zeros(num_obj,1);
for i=1:num_obj
    obj = (bwlabel(bin_image) == i);
    obj_stat = regionprops('table', obj, 'Centroid');
    obj_centroid = obj_stat.Centroid;
    distances(i) = sqrt((obj_centroid(1)-cols/2)^2+(obj_centroid(2)-rows/2)^2);
end

[~,idx] = min(distances);
obj = (bwlabel(bin_image) == idx);

% Perform dilations to smoothen the object edges
se = strel('disk', 5);
dilated = imdilate(obj, se);

% Compute the convex hull of the object
boundary = bwboundaries(dilated);
boundary = boundary{1};
k = boundary(:, 2);
l = boundary(:, 1);
k(end+1) = k(1);
l(end+1) = l(1);
mask = poly2mask(k, l, rows, cols);
vertices = bwboundaries(mask);
vertices = vertices{1};
end
1254 chars
41 lines

In the above code, we define a Matlab function find_vertices_closest_to_center that takes a binary image as input and returns the vertices of the object that is closest to the center of the image.

First, we use the regionprops function to compute the centroid of the binary image. We then compute the distance of each object's centroid from the center of the image and select the object with the minimum distance.

To smoothen the object edges, we perform dilations using a disk-shaped structuring element. We then compute the convex hull of the object and return its vertices using the bwboundaries function.

gistlibby LogSnag