user3814072
user3814072

Reputation: 9

Matlab Split an image to 8x8 2D array and save it in another array

Below is my code , i was only able to save the last array of the image ( the 88 position ) . I know the error is at line w11 but no matter how i try i cant seem to make w11 a 3D array . Help please ?

Ie=imread('Untitled-1.014.jpg');  % size 256x160
len = 256/8 ;
wid = 160/8 ;

for m = 1:8
    x1(m) = (len*m);
end

for n = 1:8
    y1(n)= (wid*n);
end

for m = 1:8
    x2(m)= (len*m)-len+1;
end

for n = 1:8
    y2(n)= (wid*n)-wid+1;
end

for m = 1:8
    for n=1:8
        w11 = Ie(x2(m):x1(m),y2(n):y1(n));
    end
end

Upvotes: 0

Views: 145

Answers (1)

CitizenInsane
CitizenInsane

Reputation: 4855

As far as I understand you want to split full 2D image in small 8x8 blocks and save all these blocks in 3D array. To do so w11 must be 3D from the beginning and you have sub-assign elements:

% The image (replaced with random data)
height = 256;
width = 160;        
Ie = rand(height, width);

% Preallocation of smaller 8x8 blocks in 3D
blocksize = 8;
nw = width / blocksize;
nh = height / blocksize;
blockCount = nw*nh;
blocks = zeros(blocksize, blocksize, blockCount);

% Splitting image
index = 1;
sub = (1:blocksize);    
for wi = 1: nw,

    wsub =  sub + (wi-1)*blocksize; % sub indices along width

    for hi = 1: nh,

        hsub = sub + (hi-1)*blocksize; % sub indices along height

        blocks(:, :, index) = Ie(hsub, wsub); % subset assignement
        index = index + 1;

    end
end

You can then access smaller block like this:

block = blocks(:,:,5); % The 5th block (of size 8x8)

NB: I put block index as last dimension in order to automatically squeeze trailing singleton dimension (this avoids calling squeeze all the time.

Upvotes: 1

Related Questions