File Exchange

image thumbnail

Embed Text and Graphics in an Image

version 3.0.5 (4.64 KB) by Brett Shoelson
Burn or embed text and graphics in an image.

8 Downloads

Updated 23 Oct 2019

View License

Use insertInImage to embed, or burn, any text or graphics item into an image. You can specify, using a cell array of parameter-value pairs (PVs), or using a structure, any valid properties of the specified object to insert.
The new version works in R2016a +, and is much improved. It now takes cell arrays of function handles (and PV pairs), so avoids multiple calls to insertInImage. Additionally, the new version no longer necessitates the visualization of a temporary figure for screen capture!
In versions prior to R16a, the function may work (back to R2014b), but may resize the image and insert a background region that will require cropping.

SYNTAX: IMGOUT = insertInImage(IMGIN,INSERTIONCOMMAND,PVs)

INPUTS:
BASEIMAGE: an image, or a handle to an image (or parent object containing an image), in which the object is to be embedded. (The image need not be displayed, unless a handle is provided.)

INSERTIONCOMMAND: text, rectangle, line, ellipse, etc. to embed in the image. Internally, insertInImage calls FEVAL; anything that works inside an feval command will workhere. For example, you can insert the string 'TESTING' at [x,y] = [20,30] using feval( @() text('TESTING',20,30]), so the insertionCommand for this would be:
@() text('TESTING',20,30).

TEXT:
@() text(x,y,string)

RECTANGLE:
@() rectangle('position',[x y w h])

LINE:
@() line(x,y)

PVs (OPTIONAL): Cell array or structure of any parameter-value pairs valid for the TYPE of object you wish to insert.(Note that this _may_ include a 'position' parameter, which will overwrite any position set with the insertion command. For example, when you insert a string, PVs can be any Parameter-Value pairs valid for TEXT objects. (See 'Text Properties' for details.)

OUTPUTS:
IMGOUT: output RGB image of the same class as imgin, with embedded text or graphic item(s).
(Thet lines, text, and circles are burned in the image herewith.)

Cite As

Brett Shoelson (2019). Embed Text and Graphics in an Image (https://www.mathworks.com/matlabcentral/fileexchange/38721-embed-text-and-graphics-in-an-image), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (25)

@KAE:
So, after some investigation, I learned that this reflects the default property-value pair in figure: 'InvertHardcopy', 'on'. I am modifying insertInImage to set that property to 'off'. That should fix this. Thanks very much for bringing it to my attention!
Brett

@KAE:
Wow...I'm stymied! I have reproduced this, but I haven't (yet) understood it. I do have a (rather strange) workaround, though. Try this: textFormat.color = [0.01 0 0];
I'm continuing to investigate what's at the root of this.
Thanks,
Brett

KAE

I seem to get the resizing behavior and the addition of a border in R2019a.

KAE

I am trying to print black text on an image which contains a lot of white. No choice of color results in black ('k', 'black', or [0 0 0]), and seems to be either white or invisible. But 'b' results in blue text, 'r' results in red, etc. What do you suggest?

KAE

KAE

Great, esp because Matlab's inserttext function doesn't come with the image processing toolbox so you have to buy the computer vision toolbox. On my first try the text looked pixelated so I will try increasing the image pixel resolution and/or font size.

John B.

roger

Works well, thanks!!

ALL:
Please note that the current version is a new one that addresses recent changes. It works in R2016a and beyond. Going back to R2014b, it will work, but may resize and border the output image. Before R14b, it will not work.
Brett

Thanks for the note, Peng.

NOTE: This function broke in R2015b, when MATLAB implemented "DPI-Aware Behavior" (see note in doc for getframe). I'm not exactly sure how to fix it (yet), but will work on it when I have time. In the meantime, I would expect it to work as planned in versions PRIOR TO R15b.

Sorry for the inconvenience.
Brett

peng wang

I had the same problem with MonoxVal. And I think the reason is this script uses 'F=getframe(ax)'(line 190), which capture the figure region. While, if the image is too big for the screen to display, Matlab will down size the image, displaying "Warning: Image is too big to fit on screen; displaying at 50%" , which causes wrong dimension for the intermediate variable. Maybe this script is no better than "text"+"getframe".

Sure, MATLAB R2015a x64

@MonoxVal:
What version of MATLAB/IPT are you using, please? I'd like to figure out what's going on.
Brett

Doesn't work for me. I download a random image, try example #1 as is, and I get an error

this is the code:
Ruta = 'C:\Users\Monox\Desktop\Pruebas.jpg';
img = imread(Ruta);
imgOut = insertInImage(img, @()text(100,200,'Test String'),...
{'fontweight','bold','color','r','fontsize',18});
figure,imshow(imgOut);

the error:
Index exceeds matrix dimensions.
Error in insertInImage/insertObject (line 192)
imgData = imgData(1:imSize(1), 1:imSize(2));
Error in insertInImage (line 141)
[imgData, bbox, clearMask] = insertObject(insertionCommand,[m,n],PVs);
Error in OtrosCodigos (line 8)
imgOut = insertInImage(img, @()text(100,200,'Test String'),...

SteveH

Thanks Brett for the quick response with updated insertInImage and additional help answering my questions. This version worked for double, unit16 & of course unit8 images. Always nice to now there are people who donate time to help others.
steve

@Steve,
Thanks for the note. I have a new version that should address this issue that I'd like to send you, if you would be amenable to testing it and giving me your feedback. I'll post it (along with a UI for it!) as soon as I can find the time to polish the UI a bit.) If you're interested, would you send me your email address?
Thanks,
Brett

@Steve,
Thanks for the note. I have a new version that should address this issue that I'd like to send you, if you would be amenable to testing it and giving me your feedback. I'll post it (along with a UI for it!) as soon as I can find the time to polish the UI a bit.) If you're interested, would you send me your email address?
Thanks,
Brett

SteveH

Hi, I'm trying to insert text on an image. I can only get the function to work if the input is uint8. does not work if input in double or uint16. this is error I get.

Error using .*
Integers can only be combined with integers of the same class, or scalar doubles.

Error in insertInImage (line 144)
imgOut(bbox(2):bbox(2)+bbox(4),bbox(1):bbox(1)+bbox(3),jj) = ...

this is the code snippet. a,b are doubles, if ZZ is double or uint16 no joy.

a=double(11);
b=double(11);
f = @()text(a,b,'Test String');
param ={'fontweight','bold','color','black','fontsize',18};
outimg = insertInImage(ZZ,f,param);

Hi Donnie, can you send me reproduction steps? An image, and a syntax for calling insertInImage?
Thanks,
Brett

Donnie Chen

Hi,
I encountered the same problem of Richa,
Error in insertInImage (line 144)
imgOut(bbox(2):bbox(2)+bbox(4),bbox(1):bbox(1)+bbox(3),jj) = ..., I debug into insertInImage, the error is caused by the line :F = getframe(ax);
imgData = F.cdata(:,:,1); F.cdata has size bigger than the baseimage's size, I guessed that getframe also takes the axes border into consideration. I google this problem, but haven't find any valid method to fix it. Could you fixed this error? Thank you.

@Richa,
Try calling insertInImage with round(bbox) as an argument. Let me know it that works for you.
Brett

Richa

Hi,

I want to save the bounding box generated by regionprops on the image. I am trying to use your function but am getting the following error:
Subscript indices must either be real positive integers or logicals.

Error in insertInImage (line 144)
imgOut(bbox(2):bbox(2)+bbox(4),bbox(1):bbox(1)+bbox(3),jj) = ...

Error in vertebrae1 (line 69)
imgOut = insertInImage(subImage,f,params);

Can you please help how to figure out this error?
Thanks and Regards
Richa

Thanks for the kind comment and review, Jan. I'm glad this is useful to you.

I haven't played with this function for a while, but I just realized that, as written, my code doesn't honor the "edgeColor" property of text--edges are rendered the same color as the text itself, regardless of how it's specified. I will work on that, but in the interim, a workaround for having a differently-colored box around text is to use a rectangle to bound to bound it.

Happy MATLABbing!
Brett

Finally the solution I searched for years. Adjustable Font-Size, Color, Font-Type, even alignment can be controlled like this: " 'HorizontalAlignment','center' ".

Thank you so much for your submission Brett.

Updates

3.0.5

Now allows specification of resolution as an input parameter. (Default remains unchanged: resolution = get(groot,'ScreenPixelsPerInch'); ). Higher resolution = better graphics. Also, Does NOT require Image Processing Toolbox.

3.0.1

I set the figure's 'invertHardcopy' property to 'off' to avoid unwanted changes of color.

3.0.0.1

Updated license

3.0.0.0

The new version works in R2016a+. (In older versions, images may be resized and require cropping.) It now takes cell arrays of function handles (and PV pairs), and no longer necessitates the visualization of a temporary figure for screen capture!

MATLAB Release Compatibility
Created with R2012b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Acknowledgements

Inspired by: createButtonLabel(string,varargin)