在MATLAB中将图像分割为子图像时,图像的一部分被删除

时间:2015-07-17 08:31:24

标签: matlab image-processing

我有336 * 104像素的图像,我需要将其分成35 * 35个子图像。但是336和104不能被35整除,因此当我将它分开时,图像的一部分被移除。我得到一个重新组装的图像,没有35 * 35像素的部分。我无法调整大小,因为如果我这样做,图像就会大不相同。这是我的代码:

% Size of the image
[H W] = size(im);

% Each sub image has 35*35 pixels
size_sub_image = 35;

% Size of each sub image
H_divided = H/size_sub_image;
W_divided = W/size_sub_image;

% Reminders allowing to take the images which are not divided
R_H = rem(H,size_sub_image);
R_W = rem(W,size_sub_image);

%Variable which is incremented and stand for each sub image
nbr_sub_images = 1;  

% Division of the image into sub images    
for i = 1:floor(H_divided)
    for j = 1:floor(W_divided)

        % R_H and R_W allow to create the sub images reminding, which have not
        %35*35 pixels. 
        %My idea was that when each i or j reach the max in the loop, the 
        %algorithm take the remindind images which have the size of R_H or R_W.
        % R_H = 21 (336 = 35*9+21) and R_W = 34 (104 = 35*2+34)

        if (i ~= floor(H_divided) && j ~= floor(W_divided))   

            nbr_sub_images = nbr_sub_images + 1;
            im_divided(:,:,nbr_sub_images) = im(size_sub_image*(i-1)+1:size_sub_image*i ,size_sub_image*(j-1)+1:size_sub_image*j );   

        end 

        if (i == floor(H_divided))

            nbr_sub_images = nbr_sub_images + 1;      
            im_divided(:,:,nbr_sub_images) = im(size_sub_image*(i-1)+1:size_sub_image*i ,size_sub_image*(j-1)+1:size_sub_image*j );

            nbr_sub_images = nbr_sub_images + 1;      
            im_divided(:,:,nbr_sub_images) = im(size_sub_image*i+1:size_sub_image*i + R_H,size_sub_image*(j-1)+1:size_sub_image*j);

        end

        if (j == floor(W_divided))

            nbr_sub_images = nbr_sub_images + 1;   
            im_divided(:,:,nbr_sub_images) = im(size_sub_image*(i-1)+1:size_sub_image*i ,size_sub_image*(j-1)+1:size_sub_image*j );

            nbr_sub_images = nbr_sub_images + 1;   
            im_divided(:,:,nbr_sub_images) = im(size_sub_image*(i-1)+1:size_sub_image*i,size_sub_image*j+1:size_sub_image*j + R_W);                 


        end

    end
end

当我执行它时,我收到错误:"订阅分配维度不匹配",但我不明白为什么,因为当我删除R_HR_W时,代码完美无缺。

1 个答案:

答案 0 :(得分:1)

据我了解,您正在尝试将不同大小的子图像放入三维数组中,这不会起作用。将二维图像添加到阵列im_divided时,所有子图像的第一维和第二维必须相同(即35x35)。有关详细信息,请参阅MATLAB documentation

有两种可能的解决方案:您可以填充图像的边缘(使用零或其他值),以便宽度和高度可以被35整除,或者使用单元格数组来存储子图像:

im_divided{nbr_sub_images} = im(rows, columns)

单元格数组能够存储不同大小的矩阵(或实际上存储各种不同的对象)。