简体   繁体   中英

Write number over an image

Using Matlab, I want to write a number in a specific position inside an image shown by imshow. At the moment, I have:

myimage = imread('Route of my image');
myimage = im2double(myimage);

imshow(myimage)

MyBox = uicontrol('style','text');
set(MyBox,'String',mynumber);
set(MyBox,'Position',[25,25,15,15]);

My problem is that positions given in 'set' are relatives to all window that manage the figure window so it also includes the gray borders. How can I write them relative to only the figure (without the gray borders)?

You could usetext instead?

imshow(image);
text(x,y,'your text')

You can follow the steps described here to remove the grey border from the figure so as to obtain right coordinates when placing the text. Basically fetch the dimensions of both the figure and axes containing the image and make the figure fit exactly the axes.

Beware that when specifying the position of a uicontrol object the 0 position is at the BOTTOM left, whereas the pixel coordinates inside an image start from the TOP left. Therefore you will need to get the dimensions of the image and subtract the actual y-coordinate from the number of rows forming the image, ie the 1st dimension.

Here is an example:

clear
clc
close all

myimage = imread('coins.png');
myimage = im2double(myimage);

imshow(myimage);

[r,c,~] = size(myimage);

%// Copied/pasted from http://www.mathworks.com/matlabcentral/answers/100366-how-can-i-remove-the-grey-borders-from-the-imshow-plot-in-matlab-7-4-r2007a
set(gca,'units','pixels'); %// set the axes units to pixels
x = get(gca,'position'); %// get the position of the axes
set(gcf,'units','pixels'); %// set the figure units to pixels
y = get(gcf,'position'); %// get the figure position
set(gcf,'position',[y(1) y(2) x(3) x(4)]);% set the position of the figure to the length and width of the axes
set(gca,'units','normalized','position',[0 0 1 1]) % set the axes units to pixels

%// Example
hold on
mynumber = 20;

%// Set up position/size of the box
Box_x = 25;
Box_y = 25;
Box_size = [15 15];
%// Beware! For y-position you want to start at the top left, i.e. r -
%// Box_y
BoxPos = [Box_x r-Box_y Box_size(1) Box_size(2)];
MyBox = uicontrol('style','text','Position',BoxPos);

set(MyBox,'String',mynumber);

and output:

在此处输入图片说明

yay!

The answers above add text on the figure window. If you want to modify your image itself and change the pixels so that you get the text where ever you display the image you can use insertText function available in Computer Vision toolbox.

myimage = imread('Route of my image');
myimage = im2double(myimage);

myimage = insertText(myimage, [25 25], 'your text');
imshow(myimage)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM