Ask an expert. Trust the answer.

Your academic and career questions answered by verified experts

How can I draw a circle on an image in MATLAB?

Date: 2022-07-18 11:15:56

I have an image in MATLAB: 

 

 im = rgb2gray(imread('some_image.jpg');
% normalize the image to be between 0 and 1
im = im/max(max(im));

And I've done some processing that resulted in a number of points that I want to highlight: 

 

points = some_processing(im);

Where points is a matrix the same size as im with ones in the interesting points.

Now I want to draw a circle on the image in all the places where points is 1.

Is there any function in MATLAB that does this? The best I can come up with is: 

 

 [x_p, y_p] = find (points);

[x, y] = meshgrid(1:size(im,1), 1:size(im,2))
r = 5;

circles = zeros(size(im));

for k = 1:length(x_p)
    circles = circles + (floor((x - x_p(k)).^2 + (y - y_p(k)).^2) == r);
end

% normalize circles
circles = circles/max(max(circles));

output = im + circles;

imshow(output)

This seems more than somewhat inelegant. Is there a way to draw circles similar to the line function? 

Answers: 

You could use the normal PLOT command with a circular marker point: 

 

 [x_p,y_p] = find(points);
imshow(im);         %# Display your image
hold on;            %# Add subsequent plots to the image
plot(y_p,x_p,'o');  %# NOTE: x_p and y_p are switched (see note below)!
hold off;           %# Any subsequent plotting will overwrite the image!

You can also adjust these other properties of the plot marker: MarkerEdgeColorMarkerFaceColorMarkerSize.

If you then want to save the new image with the markers plotted on it, you can look at this answer I gave to a question about maintaining image dimensions when saving images from figures.

NOTE: When plotting image data with IMSHOW (or IMAGE, etc.), the normal interpretation of rows and columns essentially becomes flipped. Normally the first dimension of data (i.e. rows) is thought of as the data that would lie on the x-axis, and is probably why you use x_p as the first set of values returned by the FIND function. However, IMSHOW displays the first dimension of the image data along the y-axis, so the first value returned by FIND ends up being the y-coordinate value in this case.


Why Matlabhelpers ?

Our Matlab assignment helpers for online MATLAB assignment help service take utmost care of your assignments by keeping the codes simple yet of high-quality. We offer the most reliable MATLAB solutions to students pursuing their Computer Science course from the Monash University, the University of Sydney, the University of New South Wales, the University of Melbourne; to name a few. Approach us today for best Matlab solutions online!

whatsApp order on matlabhelpers.com

telegram order on matlabsolutions.com