# How to display a number of black tiles on a figure

1 view (last 30 days)
Arnold on 19 Nov 2022
Commented: Arnold on 19 Nov 2022
This is my code
A = ones(100,100);
for j = 1:100
if j <= 50
A(j, 1:51-j) = 0;
elseif (51 <= j) && (j <= 75)
A(j,j:75) = 0;
elseif (j >= 76) && (j <= 85)
A(j, 26:50) = 0;
else
A(j, 26:50) = 0;
A(j, 1:j-85) = 0;
A(j, 100-(j-86):100) = 0;
end
pause(0.01)
imshow(A)
end
But how would I go about calculating the number of black tiles in the generated figure and to display the number of black tiles on the figure itself?
Arnold on 19 Nov 2022
Note, this is my first time ever in coding. So what may seem obvious to some, is completely alien to me.

DGM on 19 Nov 2022
Edited: DGM on 19 Nov 2022
Depends what you mean by "tiles", and it depends what you want to do with the output. This might help.
A = ones(100,100);
for j = 1:100
if j <= 50
A(j, 1:51-j) = 0;
elseif (51 <= j) && (j <= 75)
A(j,j:75) = 0;
elseif (j >= 76) && (j <= 85)
A(j, 26:50) = 0;
else
A(j, 26:50) = 0;
A(j, 1:j-85) = 0;
A(j, 100-(j-86):100) = 0;
end
pause(0.01)
imshow(A)
end
% if "tiles" means "pixels"
ntiles = nnz(~A)
ntiles = 2465
% if "tiles" means "objects"
[~,ntiles] = bwlabel(~A)
ntiles = 5
% put some chosen text on the figure
ht = text(60,25,sprintf('there are %d tiles',ntiles)); If your goal is to make something for display purposes, that might be fine. You can set the properties (font/size/color) of the text object as you wish.
If your goal is to produce an accurate binarized image and save it to a file, this wouldn't be a good way to do it though. Saving the figure would give you the above image, but it is neither binarized, nor is it 100x100 anymore. It can't be; there wouldn't be enough resolution to render the text at that size.
If you want to maintain the resolution of a small binarized image and still be able to put text into it, that's what MIMT textim() is good at. It can generate small logical images of text. The rest is just inserting the text into the image.
% generate text image
ntiles = nnz(~A); % whatever text you want
%tpict = ~textim(sprintf('%d',ntiles),'hp-100x-11x10'); % pick a font
%tpict = ~textim(sprintf('%d',ntiles),'hp-100x-8x6');
tpict = ~textim(sprintf('%d',ntiles),'tinynum');
% calculate indices
os = [20 50];
szt = imsize(tpict,2);
xrange = os(2):os(2)+szt(2)-1;
yrange = os(1):os(1)+szt(1)-1;
% insert tpict into A
A(yrange,xrange) = tpict;
imwrite(A,'things.png')   Of course, the text still has to fit within the image.
Arnold on 19 Nov 2022
Ah I see, thank you so much ^_^