2017-03-24 29 views
1

我想將圖像分成8乘6塊,然後從每個塊想要得到紅色,綠色和藍色值的平均值,然後將每個塊的平均值存儲到一個數組中。說,如果我有圖像分成4塊,結果數組將是:Matlab:通過圖像塊迭代

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 

回答

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