How to divide an image into blocks and find the RGB values of each pixels in a block?
1 次查看(过去 30 天)
显示 更早的评论
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].
0 个评论
回答(1 个)
Thorsten
2015-5-26
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 个评论
Thorsten
2015-5-27
编辑:Thorsten
2015-5-27
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Image Processing Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!