Reputation: 1
when i try to resize an image by computing the average of 4 pixels to get one pixel, i got a problem, and following are my code, help me please, it's driving me crazy
a=imread('c:\black and white.jpg');
[rows,columns,phases]=size(a);
i=1;j=1;k=1;
c=zeros(rows/2,columns/2,phases);
c=uint8(c);
for x=1:2:rows-1;
for y=1:2:columns;
for z=1:phases;
c(i,j,k)=1/4*(a(x,y,z)+a(x,y+1,z)+a(x+1,y,z)+a(x+1,y+1,z));
k=k+1;
end
j=j+1;
k=1;
end
i=i+1;
j=1;
k=1;
end
figure, imshow(a)
figure, imshow(c)
Upvotes: 0
Views: 1257
Reputation: 21563
Perhaps your question is as simple as this, assuming you have a image called myImage
:
First make sure the number of pixels in each direction is even
myImage = myImage(1:fix(end/2)*2,1:fix(end/2)*2)
Then take the average of each 4 pixels
(myImage(1:2:end,1:2:end)+myImage(2:2:end,1:2:end)+ ...
myImage(1:2:end,2:2:end)+myImage(2:2:end,2:2:end))/4
Note that this assumes that you don't mind losing the last row or column of pixels, otherwise you need to do something smarter.
Upvotes: 0
Reputation: 112659
You can do it without loops, by computing block averages along each column and then alog each row, as follows.
I am assuming your data is an image, i.e. a 2D array. If you have a 3D array with several images piled along the 3rd dimension (as it seems to be in your code), just apply this to each image (that is, for each value of the 3rd index).
Matrix size and block size are arbitrary, as long as block size divides the number of rows and columns of the input matrix a
.
a = rand(100,120); % example data
n = 2; % block size
m = size(a)/n; % assumed to be integer
c = reshape(mean(reshape(a,n,[])),m(1),[]).'; % mean by colummns in groups of n
c = reshape(mean(reshape(c,n,[])),m(2),[]).'; % mean by rows in groups of n
Upvotes: 1