简体   繁体   中英

exchange circle pixels in an image in matlab

All I want is to add a circle into an image of a radius and centre of my choice, however I DO NOT WANT to use plot COMMAND, I want a new output array which has my chosen image and circle on it. here is my function

function [ out_image ] = draw_circle( in_image,x0,y0,r,value)

where in_image is the input image x0 y0 he centre of circle and r the radius value the intensity of image

this is my attempt which does not work

ang=0:pi/100:2*pi
x=r*cos(ang)+x0;
y=r*sin(ang)+y0;
cir=[x,y];
[j,k]=size(cir);
for cir=1:j
    for cir=1:k     
if cir(i,j)==0
out_image(i,j)=in_image(i,j);
end
end
end

imshow(out_image)

end

I'm pretty sure there are better ways, but following your approach, you might use the following code:

out_image = in_image;
cir = round([r*cos(ang)+x0;r*sin(ang)+y0]);
for i = 1:size(cir,2)
    out_image(cir(1,i),cir(2,i),:) = 255;
end

Your for loops did not work the way you wrote them. Also, you should use round to get indices, and not floating point values. However, the circle is quite small (only 1 pixel), which might not be enough for large pictures. See example below. Also, you might need a finer discritization for large pictures, ie a larger number of elements in ang . 在此处输入图片说明

In case you want a larger linewidth , you can use

lw = 3; % Enter linewidth here
for i = 1:size(cir,2)
    out_image(cir(1,i)+(-lw:lw),cir(2,i)+(-lw:lw),:) = 255;
end

在此处输入图片说明 EDIT: In case you don't see it. The circle is close to the top left corner.

The complete code for the function is:

function [ out_image ] = draw_circle( in_image,x0,y0,r,value,lw)

out_image = in_image;
ang = 0:pi/100:2*pi;
cir = round([r*cos(ang)+x0;r*sin(ang)+y0]);
for i = 1:size(cir,2)
    out_image(cir(1,i)+(-lw:lw),cir(2,i)+(-lw:lw),:) = value;
end
imshow(out_image)

You can call it from command line with

draw_circle(in_image,100,200,50,0,3);

Note, I took the unused value as grayscale value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM