【问题标题】:Matlab: iterate through image blocksMatlab:遍历图像块
【发布时间】:2017-08-17 21:26:27
【问题描述】:

我想将图像分成 8 x 6 个块,然后从每个块中获取红色、绿色和蓝色值的平均值,然后将每个块的平均值存储到一个数组中。假设我将图像分成 4 个块,结果数组将是:

A = [average_red, average_green, average_blue,average_red, ...
  average_green, average_blue,average_red, average_green, ...
  average_blue,average_red, average_green, average_blue,...
  average_red, average_green, average_blue,]

我创建的循环看起来非常复杂,需要很长时间才能运行,我什至不确定它是否正常工作,因为我不知道如何检查。有没有更简单的方法来实现这个。

这是循环:

[rows, columns, ~] = size(img);

[rows, columns, ~] = size(img);

rBlock = 6;
cBlock = 8;
NumberOfBlocks = rBlock * cBlock;

bRow = ceil(rows/rBlock);
bCol = ceil(columns/cBlock);

row = bRow;
col = bCol;

r = zeros(row*col,1);
g = zeros(row*col,1);
b = zeros(row*col,1);

n = 1;
cl = 1;
rw = 1;

for x = 1:NumberOfBlocks

    for i = cl : col
        for j = rw : row
         % some code
        end
    end

    %some code
    if i == columns && j ~= rows
        cl = 1;
        rw = j - (bRow -1);
        col = (col - col) + bCol;
        row = row + bRaw;

    elseif a == columns && c == rows
        display('done');
    else
        cl = i + 1;
        rw = j - (bRow -1);
        col = col + col;
        row = row + row;
    end

end

【问题讨论】:

    标签: matlab loops for-loop image-processing iterator


    【解决方案1】:

    因为只有 48 个块,你可以使用简单的 for 循环迭代块。 (我认为它会足够快)。

    这是我的代码:

    %Build test image
    img = double(imresize(imread('peppers.png'), [200, 300]));
    
    [rows, columns, ~] = size(img);
    
    rBlock = 6;
    cBlock = 8;
    NumberOfBlocks = rBlock * cBlock;
    
    bRow = ceil(rows/rBlock);
    bCol = ceil(columns/cBlock);
    
    idx = 1;
    
    A = zeros(1, rBlock*cBlock*3);
    
    for y = 0:rBlock-1
        for x = 0:cBlock-1
            %Block (y,x) boundaries: (x0,y0) to (x1,y1)
            x0 = x*bCol+1;
            y0 = y*bRow+1;
            x1 = min(x0+bCol-1, columns); %Limit x1 to columns
            y1 = min(y0+bRow-1, rows);    %Limit y1 to rows
    
            redMean   = mean2(img(y0:y1, x0:x1, 1));    %Mean of red pixel in block (y,x)
            greenMean = mean2(img(y0:y1, x0:x1, 2));    %Mean of green pixel in block (y,x)
            blueMean  = mean2(img(y0:y1, x0:x1, 3));    %Mean of blue pixel in block (y,x)
    
            %Fill 3 elements of array A.
            A(idx)   = redMean;
            A(idx+1) = greenMean;
            A(idx+2) = blueMean;
    
            %Advance index by 3.
            idx = idx + 3;
        end
    end
    

    【讨论】:

      猜你喜欢
      • 2014-04-08
      • 2016-10-25
      • 2016-10-30
      • 2017-04-30
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多