Azzera filtri
Azzera filtri

How to add text to an image

58 visualizzazioni (ultimi 30 giorni)
Nikhil Hegde
Nikhil Hegde il 4 Nov 2015
Risposto: DGM il 21 Ott 2022
I've this code that adds a bounding box to all the cashews present in an image. The image is attached.
rgbImg = imread('White Wholes 500.jpg');
img = rgb2gray(rgbImg);
se = mmseline(2);
img1(:, :, 1) = mmasf(img, 'OC', se, 3);
T = uint8 (round( max(max(img1(:, :, 1))) * graythresh(img1(:, :, 1)) ));
X = mmthreshad (img1 (:, :, 1), T);
X = ~X;
X = imclose(X, true(5));
X = ~X;
stats = regionprops(bwlabel(X),'Area','Centroid','Perimeter','BoundingBox');
Boxes=cat(1,stats.BoundingBox);
maskm = false(size(X,1),size(X,2));
for k1 = 1:size(Boxes,1)
mask1 = false(size(X,1),size(X,2));
starty = round(Boxes(k1,1));
stopy = starty+round(Boxes(k1,3))-1;
startx = round(Boxes(k1,2));
stopx = startx+round(Boxes(k1,4))-1;
text(startx,starty,'Box1');
mask1(startx:stopx,starty:stopy) = true;
maskm = maskm + imdilate(edge(mask1,'sobel'),strel('disk',2));
end
maskm = maskm + X;
figure,imshow(maskm);
To label each box I can put it in a for loop I get that. I just wanted to know how I add text to a bounding box.I didn't understand the 'text' function in MATLAB so if your answer uses the 'text' function, then if you could please explain in brief the functionality then that would be great for me!

Risposta accettata

Image Analyst
Image Analyst il 4 Nov 2015
You got x and y reversed. Confusing row,column with x,y (reversing the correct order) is a very common mistake. Bounding box is (x,y, width, height). You have startY = Boxes(k1,1) when it should be Boxes(k1, 2) since y is the second element, not the first.

Più risposte (2)

Thorsten
Thorsten il 4 Nov 2015
The text function just draws the text into the image at position x,y. The default text color is black. So if you want to draw text on black background, you have to specify a visible color, like
text(startx,starty,'Box1', 'Color', 'r');

DGM
DGM il 21 Ott 2022
For passers-by:
There are other ways to add text to an image without relying on using the figure as an ad-hoc compositor and potentially ruining the image resolution.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by