Draw rectangles on an image in Matlab

Use getframe

img = imread('cameraman.tif');
fh = figure;
imshow( img, 'border', 'tight' ); %//show your image
hold on;
rectangle('Position', [50 70 30 60] ); %// draw rectangle on image
frm = getframe( fh ); %// get the image+rectangle
imwrite( frm.cdata, 'savedFileName.png' ); %// save to file

See rectanlge for more options on drawing rectangles. The 'Position' argument for rectangle is in format [from_x from_y width height] and is given in units of pixels.


The best and easy way to use is in the updated Matlab versions

img = imread('abcd.jpg');
box = [X1, Y1, width, height];    
outImage= insertObjectAnnotation(img,'rectangle',bbox,'Rectangle');
figure, imshow(outImage), title('Image with rectangle');

Without using getframe:

im=imread('face.jpg'); %Image read
rectangle('Position', [10 10 30 30] ,...
    'EdgeColor', 'r',...
    'LineWidth', 3,...
    'LineStyle','-');%rectangle properties
imshow( im, rectangle); %draw rectangle on image.

For more detail visit this MathWorks thread :)

Tags:

Matlab