How to divide an image into blocks and find the RGB values of each pixels in a block?
Show older comments
How to divide an image into blocks and find the RGB values of each pixels in a block? I used the following code to divide an image into blocks of size 32*32
J = imresize(M1, [256 256]);
[r c]=size(J);
bs=32; % Block Size (32x32)
nob=64 % Total number of 32x32 Blocks
% Dividing the image into 32x32 Blocks
kk=0;
l=0;
[F]=zeros(1,64);
%[B0]=zeros(32,32);
for i=1:(r/bs)
for j=1:(c/bs)
B0=J((bs*(i-1)+1:bs*(i-1)+bs),(bs*(j-1)+1:bs*(j-1)+bs),3);
end
kk=kk+(r/bs);
end
% And to get the RGB values I used the following code
for x=1:32
for y=1:32
R=B0(x,y,1);
G=B0(x,y,2);
B=B0(x,y,3);
end
end
But it shows the error
Attempted to access B0(1,1,2); index out of bounds because size(B0)=[32,32,1].
Answers (1)
Thorsten
on 26 May 2015
To get the i,j 32x32 block from an RGB image, use
BL = I((i-1)*32+[1:32], (j-1)*32+[1:32], 1:3);
to select the R,G,B planes from this block, use
R = BL(:,:,1); G = BL(:,:,2); B = BL(:,:,3);
6 Comments
Anushka
on 26 May 2015
Anushka
on 26 May 2015
I tested it with
J = imread('peppers.png');
J = J(1:256, 1:256, :);
and it worked smoothly.
Note that you do not need the kk = kk + ... line and the nob = 64 line.
Also, so far you are just assigning 64 times a different subimage of J to BL, without doing anything with BL. So at the end of the loop, BL ist just the bottom right 32x32 subimage of J.
Anushka
on 27 May 2015
I do not have to initialize BL; There is a bug in your code in the innocent looking line
[r c]=size(J);
For color images, c would be the number of columns *3, and this results in out of range errors in the for-loop. Instead, use
r = size(J, 1); c = size(J, 2);
Here is the full example:
J = imread('peppers.png');
J = J(1:256, 1:256, :);
r = size(J, 1); c = size(J, 2);
bs=32; % Block Size (32x32)
for i=1:(r/bs)
for j=1:(c/bs)
BL=J((i-1)*32+[1:32],(j-1)*32+[1:32],1:3);
imshow(BL), pause % show for testing
R = BL(:,:,1); G = BL(:,:,2); B = BL(:,:,3);
imshow([R G B]), pause % show for testing
end
end
Categories
Find more on Neighborhood and Block Processing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!