how can I draw a rectangle on a image?
显示 更早的评论
Hello friends I'm with a problem! I have a vector with x and y coordinates and I need to draw a rectangle over an image.A rectangle with the dimensions 3x3 with the red line from the centroid point how can I do this?
采纳的回答
更多回答(2 个)
Dima Lisin
2015-6-19
0 个投票
Hi Biza,
Try using the insertShape function in the Computer Vision System Toolbox.
Edwards Ramirez
2019-1-22
I had to write it on my own. Here the used function:
function imageReturn = drawRectangle(image, Xmin, Ymin, width, height)
imageReturn = image;
intensity = 255;
X1 = Ymin;
Y1 = Xmin;
X2 = Ymin + width;
Y2 = Xmin + height;
Xcenter = round((X1+X2)/2);
Ycenter = round((Y1+Y2)/2);
for i=X1:X2
imageReturn(i,Y1,1)=intensity;
end
for i=X1:X2
imageReturn(i,Y2,1)=intensity;
end
for i=Y1:Y2
imageReturn(X1,i,1)=intensity;
end
for i=Y1:Y2
imageReturn(X2,i,1)=intensity;
end
%Comment the following for cycles if you don't want the cross in the centroid
for i=Xcenter-3:Xcenter+3
imageReturn(i,Ycenter,1)=intensity;
end
for i=Ycenter-3:Ycenter+3
imageReturn(Xcenter,i,1)=intensity;
end
end
1 个评论
Image Analyst
2019-1-22
编辑:Image Analyst
2019-1-22
Well, okay. Your code burns the rectangle into the image (although it's very confusing because you're setting x equal to y and y equal to x instead of just doing it like you should). The poster said he wants to "draw a rectangle over an image", which I take to mean in the graphical overlay over the image, not INTO the image itself. You could put a rectangle into the graphical overlay over the image with the rectangle() function. If you want to burn the rectangle into the image, one could use insertShape like Dima said in his answer (though it requires the Computer Vision System Toolbox).
By the way, your for loops could be vectorized, so
for i=X1:X2
imageReturn(i,Y1,1)=intensity;
end
would become
imageReturn(Ymin, XMin:(Xmin + width - 1), 1) = intensity;
Notice that I corrected your confusing indexing. It's a very common beginner mistake and that is thinking arrays are indexed as (x,y) instead of (y, x). I know you tried to correct it with your swapping of x and y but I personally think that just made it more confusing. Arrays are indexed as (row, column), so the first index is row, or Y, not X as you had it.
You might want to edit your code and correct that lest anyone every copy it and try to use it and run into problems that confuse them.
类别
在 帮助中心 和 File Exchange 中查找有关 Computer Vision Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!