How can I create a rectangle with an outlined border?
Asked Answered
B

3

6

I want to draw a rectangle to outline an area of an image that I've plotted in one axes of a figure. I have multiple axes in this figure, so I am using the rectangle() function. What I want is to draw a white rectangle a thin black border just inside and just outside the rectangle. The part of the image inside the rectangle should be visible, so all 'facecolor' should be 'none'. I have tried drawing 3 rectangles, two black ones with thin linewidths and one thicker white one, but the problem is that 'Position' is defined in axes units and 'LineWidth' is defined in point units, so that the scaling doesn't work too well, especially when the figure is resized.

FYI, the outline is so that the white rectangle is more visible against a light background. The images plotted vary widely, so a single color won't be universally visible for my data.

Any suggestions on how I can do this?

Botanomancy answered 13/2, 2012 at 20:24 Comment(0)
C
7

How about just using different line widths 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 MATLAB figure than as PNG file.

Better with getframe:

cameraman with rectangle (getframe)

Cali answered 13/2, 2012 at 20:34 Comment(1)
Works quite well for adding rectangles to normal MATLAB plots, too.Farron
T
3

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

You could also calculate the mean value of the pixels inside the rectangle, and set the box color to the inverse. In 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',[x y w h],'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
Trip answered 13/2, 2012 at 21:18 Comment(0)
P
2

Yuk's solution works quite well for adding a rectangle to a normal MATLAB plot, too. The 'position' values are not interpretet as pixels but are adjusted to the plot values (see 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 results in the following plot: enter image description here

Polyclitus answered 31/12, 2013 at 9:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.