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

조회 수: 28 (최근 30일)
Tamara del Águila
Tamara del Águila 2021년 5월 23일
댓글: Tamara del Águila 2021년 5월 24일
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)

채택된 답변

Rik
Rik 2021년 5월 23일
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
Rik
Rik 2021년 5월 24일
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 2021년 5월 24일
sorry, I didn't know it worked like this... thanks for that piece of information as well!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Images에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by