从加扰图像中排除白色方块

时间:2014-08-27 06:11:18

标签: image matlab image-processing shuffle

所以我有一段代码可以切掉图像的正方形并加扰它们。我有一系列面孔在白色背景上。我想要做的是从随机图像中随机取一个正方形以添加到最终的加扰图像中,但如果该正方形为白色则不行。

这是代码:

%%首先获取图像的大小并将其划分为30像素的块

n = 30;
image_size = imread(all_images{1});
mn = floor(size(image_size)/n);
m1 = mn(1);
n1 = mn(2);

%加扰块的新矩阵

newim = zeros(m1*n,n1*n);

%文件中有51张图片

for bb = 1:51   
for k = 1:m1*n1
     good_squares = false;
     while ~good_squares


current_image = randsample(1:51, 1);
my_image = imread(all_images{current_image});


ind = randperm(m1*n1);
[ind1, ind2] = ind2sub([m1, n1], ind);
[i,j]=ind2sub([m1, n1], k);


newim((i-1)*n+1:i*n, (j-1)*n+1:j*n) = ...
my_image((ind1(k)-1)*n+1:ind1(k)*n,(ind2(k)-1)*n+1:ind2(k)*n);


x = my_image((ind1(k)-1)*n+1:ind1(k)*n,(ind2(k)-1)*n+1:ind2(k)*n);
good_squares = true;

       if x(1, 1) == 255 && x(1, 30) == 255 && x(30, 1) == 255 
           good_squares = false;
       elseif x(1, 1) == 255 && x(1, 30) == 255 && x(30, 30) == 255
           good_squares = false;
       elseif x(30, 1) == 255 && x(30, 30) == 255 && x(1, 30) == 255
           good_squares = false;
       end
      end
end
%   write out new mask
         imwrite(newim, ['mask' num2str(bb) '.bmp'],'bmp');
end

所以我运行代码的排除部分(good_blocks = false)我试图排除一个块,如果三个角中的像素是白色的。此代码吐出51个纯白色图像,因此索引被破坏,或者while循环不正确。任何关于如何做到这一点的建议都表示赞赏。

1 个答案:

答案 0 :(得分:1)

我认为你的子索引随机数发生器没有任何问题(尽管我没有花时间思考当图像不是灰度时会发生什么,即有三维)。

我觉得你的白色不是纯白色,所以可能会尝试这样的东西:

for bb = 1:51
  for k = 1:(m1*n1)
    good_squares = false;
    while ~good_squares

      %%...

      threshold = 230 % adapt this value to your needs      
      if any(x < threshold)
        good_squares = true;
      end

    end
  end

  % write out new mask  
  %% ...

end

条件也可能是这样的:

threshold_value = 230
threshold_pixelCount = 5

if sum(x < threshold_value) > threshold_pixelCount
    good_squares = true;
end