Error in splitting image into blocks of pixels in matlab
I am trying to split an image into 16x16 blocks here is my code
A = imread('telec.jpg'); %reads file into a matrix
B = rgb2ycbcr(A); %reads file info
%convert to YCbCr
%if B.Format=='bmp'
% A=rgb2ycbcr(A)
[width height]=size(B);
%detirmine number of 8x8 matrices, use ceil to round up
W=ceil(width/8);
H=ceil(height/8);
%create a matrix of zeros and add the image to it to fill out the 8x8
%matrices (matrix will stay the same size if height and width are
%divisible by 8
I=zeros(H*8,W*8,'uint8');
I(1:height,1:width)=B(1:height,1:width);
%divide numbers into WxH 8x8 matrices
X=zeros(H,W,8,8);
for J=1:H
for K=1:W
for j=1:8
for k=1:8
X(J,K,j,k)=I((J-1)*8+j,(K-1)*8+k);
end
end
end
end
i get the following:
??? The index exceeds the size of the matrix.
Error in ==> projet at 18
I (1: height, 1: width) = B (1: height, 1: width); can anyone help? thank you in advance
source to share
Assuming the dimensions of the input matrix 2D
I
are divisible by blockize perfectly 8
, alternatively you can use a no-loop approach that uses a pair and to achieve your output array - reshape
permute
4D
X
%// About script: Blockwise split a 2D array into a 4D array
%// Input(s): I (Input 2D array), N (Blocksize)
%// Output(s): X (Output 4D array)
N = 8; %// blocksize
[m,n] = size(I); %// Size of 2D input array
X = permute(reshape(permute(reshape(I,N,m/N,[]),[1 3 2]),N,N,n/N,[]),[1 2 4 3])
Run example (s blocksize = 2
) -
I =
0.6414 0.4333 0.1077 0.3413 0.0226 0.6582
0.1388 0.5903 0.8644 0.7008 0.1167 0.8336
0.0079 0.4648 0.4698 0.4513 0.6500 0.8422
0.5720 0.1261 0.4916 0.7439 0.0378 0.8782
X(:,:,1,1) =
0.6414 0.4333
0.1388 0.5903
X(:,:,2,1) =
0.0079 0.4648
0.5720 0.1261
X(:,:,1,2) =
0.1077 0.3413
0.8644 0.7008
X(:,:,2,2) =
0.4698 0.4513
0.4916 0.7439
X(:,:,1,3) =
0.0226 0.6582
0.1167 0.8336
X(:,:,2,3) =
0.6500 0.8422
0.0378 0.8782
source to share