How to bin data from a matrix (2D array)

29 vues (au cours des 30 derniers jours)
Tamara del Águila
Tamara del Águila le 23 Mai 2021
I am trying to downsample a matrix that contains data that sum up to 100 (cdata, it's % data for each pixel) by summing up the % corresponding to each new bin of size npix*npix.
However, I am loosing data for some reason, as it can be somehow seen in the image (and in the title the sum of the binned matrix, you can see how much it sums up, that's never 100%).
The code I have used is below... could anyone help figure out what's the problem?
Else, if there is a more efficient or simpler way of doing it, I'd appreciate it. In the beginning I tried with 'resample' but there is no option of summing up instead of using averages...
xdim = size(cdata,1);
ydim = size(cdata,2);
npix = 10; % number of
n_xbin = ceil(xdim/npix); %ceil to prevent loosing pixels outside the boundaries of the new matrix
n_ybin = ceil(ydim/npix);
cdata2bin = cdata; % original colour data
cdata2bin(xdim:n_xbin*npix+1 , ydim:n_ybin*npix+1) = 0; % fill with zero so the loop cn cover the whole matrix
% build new binned matrix
x = 1;
for xbin = 1:n_xbin
y = 1;
for ybin = 1:n_ybin
databin = cdata(x:x+npix-1, y:y+npix-1);
binned(xbin, ybin) = sum(databin(:));
y = y+npix-1;
end
x = x+npix-1; %skip the bin
end
sum(cdata(:)) % sum up to 100%
sum(binned(:)) %should sum up to 100%... but it does not! (as it can be seen in the image)

Réponse acceptée

Rik
Rik le 23 Mai 2021
If you have the image processing toolbox, you can use blockproc to do the calculation. If you don't mind the overhead, you could also use mat2cell to split your image and use a loop or cellfun to sum elements.
  3 commentaires
Rik
Rik le 24 Mai 2021
You're welcome. If I solved your question, please consider marking it as accepted answer. If not, feel free to comment with your remaining issues.
Tamara del Águila
Tamara del Águila le 24 Mai 2021
sorry, I didn't know it worked like this... thanks for that piece of information as well!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Images dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by