How to create a rectangle with a selected border?

I want to draw a rectangle to outline the area of โ€‹โ€‹the image that I built on one axis of the shape. I have several axes in this figure, so I use the rectangle () function. I want to draw a white rectangle with a thin black frame just inside and right behind the rectangle. Part of the image inside the rectangle should be visible, so all "facecolor" should be "none". I tried to draw 3 rectangles, two black ones with thin line widths and one thicker white one, but the problem is that "Position" is defined in units of axes, and "LineWidth" is defined in units of points, so scaling does not work too well, especially when the image size changes.

FYI, the outline so that the white rectangle is more visible on a light background. The images depicted vary widely, so one color will not be displayed for my data.

Any suggestions on how I can do this?

+6
source share
3 answers

How to use only line width for black and white rectangle?

imshow('cameraman.tif') rectangle('position',[80 30 100 100],'edgecolor','k','LineWidth',4) rectangle('position',[80 30 100 100],'edgecolor','w','LineWidth',1) 

cameraman with rectangle (Save As)

Hmm, the corners look much better on a MATLAB figure than in a PNG file.

Better with getframe :

cameraman with rectangle (getframe)

+7
source

I like the @Yuks solution. But there is another possibility that you might consider:

You can also calculate the average pixel value inside the rectangle and set the window color to the opposite. This way you will always have a good contrast.

enter image description here

Here is the code:

 function PlotRect(im,x,y,w,h) m = double(im( round(y): round(y+h) , round(x): round(x+w),:)); if (mean(m(:)) < 255/2) col = [1 1 1]; else col = [0 0 0]; end rectangle('Position',[xywh],'EdgeColor', col); end 

And the test:

 function Inverse() im = imresize( uint8(0:5:255), [250, 400]) ; figure;imshow(im); hold on; PlotRect(im,5,8,50,75); PlotRect(im,100,30,25,42); PlotRect(im,200,10,40,40); PlotRect(im,300,10,40,40); end 
+3
source

Yuk's solution works well enough to add a rectangle to the normal MATLAB graph. The "position" values โ€‹โ€‹are not interpreted as pixels, but are adjusted for the values โ€‹โ€‹of the graph (see the code example below):

 figure; plot(0:10,0:10); grid on; hold on; rectangle('position',[1 1 8.5 8.5],'LineWidth',2); hold off; 

This code leads to the following graph: enter image description here

+2
source

Source: https://habr.com/ru/post/908370/


All Articles