I'm trying to calculate the area total area of scattered squares just like the image below.
I know there are a function with which we could estimate the area size by making a comprehensive convex, but I'm not sure whether I can use some similar method to solve this.
Does anyone has a good idea?
Edit[01/01/2016]: The code I tried is like this. It works, but every time it has to save and load a .png image. I wanted to ask if it is possible to calculate the size without the process of saving images.
clear
b=zeros(127,2); %matrix
for i=1:127
rnd=randn(1,2);
b(i,:)=30.*rnd;
end
BW=scatter(b(:,1),b(:,2),15,[],'r','s','filled');
view(2) %view from Z+
axis off
saveas(gcf,'scatter.png')
close all
BWbase = imread('scatter.png'); %import
BW = im2bw(BWbase,0.5); %convert to binary data
imshow(BW);
bwarea(BW)
You do not need to save and load the image if you know proper functions. Your code has some issues that I fixed and I will explain here:
1- you do not need to initialize b
with zeros and then fill it using a for-loop by random values. Instead you can do all that in one line of code:
b = 30 * randn(127,2);
2- Then you plot the points using scatter
. I have removed []
to fix the command.
BW = scatter(b(:,1),b(:,2),15,'r','s','filled');
Note that this is not an image but a figure that you need to convert to an image. The function you are seeking is getframe
. This function records a frame from a figure. You can call it by providing it with the current figure gcf
.
F = getframe(gcf);
4- Now your frame in stored in F
but it is not an image yet. To convert it to an image you need to use frame2im
function.
[X, Map] = frame2im(F);
5- Then, as you did yourself, you convert the image to binary and calculate the area:
BW2 = im2bw(X,0.5);
bwarea(BW2)
The whole code can be seen here:
b = 30 * randn(127,2);
BW = scatter(b(:,1),b(:,2),15,'r','s','filled');
axis off
F = getframe(gcf);
[X, Map] = frame2im(F);
BW2 = im2bw(X,0.5);
imshow(BW2);
bwarea(BW2)
For more information check out the following documentations: getframe, frame2im.