2016-03-14 66 views

回答

0

創建checkboard模式的最簡單方法可能是創建一個矩形網格(ndgrid),然後使用mod查找所有列和行索引總和爲偶數的元素。

sz = size(rgbImage); 
[row, col] = ndgrid(1:sz(1), 1:sz(2)); 
checkers = logical(mod(row + col, 2)); 

另一種方法來創建這個相同的邏輯checkers矩陣是使用bsxfun,這將大大減少由先前的操作佔用的內存。

checkers = bsxfun(@(x,y)mod(x + y, 2), 1:size(rgbImage, 1), (1:size(rgbImage, 2)).').'; 

enter image description here

現在我們只需要使用索引此邏輯矩陣爲rgbImage並設置相關的值,以灰色(128)。一個簡單的方法是平滑rgbImage的第一維,以便我們可以直接用邏輯矩陣checkers來索引它們。

reshaped_image = reshape(rgbImage, [], 3);   % Flatten first two dims 
reshaped_image(checkers, :) = 128;     % Set all channels to 128 
newImage = reshape(reshaped_image, size(rgbImage)); % Shape it back into original 

enter image description here

更新

如果你想這個棋盤圖案應用到白色部分原來的rgbImage的,你絕對可以做到這一點。爲此,您需要創建一個邏輯矩陣,指示白色像素的位置。然後,您想查找棋盤圖案的位置AND(&),其中像素爲白色。

isWhite = all(rgbImage == 255, 3);  % White pixels where all channels = 255 
tochecker = checkers & isWhite;  % Combine with checkerboard 

然後以相同的方式應用此模式。

reshaped_image = reshape(rgbImage, [], 3);   % Flatten first two dims 
reshaped_image(tochecker, :) = 128;     % Set all channels to 128 
newImage = reshape(reshaped_image, size(rgbImage)); % Shape it back into original 

如果我們在您的文章將此到圖像,我們得到以下

enter image description here

1

1)讀出的圖像:

rgbImage = imread('photo.jpg'); 

2)轉換爲一個單元陣列,其中每個元素代表一個像素雖然1x1x3 UINT8 RGB三元:

cellArray = mat2cell(rgbImage, ones(size(rgbImage,1),1), ones(size(rgbImage,2),1), size(rgbImage,3)); 

3)用灰色替換每個第二個單元格。請注意,我們需要保留原始類型和尺寸,否則以下cell2mat調用將失敗:

cellArray(1:2:end) = {reshape(uint8([255,255,255]*0.1), [1,1,3])}; 

4)轉換回矩陣,顯示:

imageGray = cell2mat(cellArray); 
imshow(imageGray); 

編輯棋盤

如果要將圖像着色爲棋盤格,則不管圖像尺寸如何,步驟3可以替換爲:

linInd = 1:numel(cellArray); 
[i,j] = ind2sub(size(cellArray), linInd); 
toColor = mod(i+j,2) == 0; 
cellArray(linInd(toColor)) = {reshape(uint8([255,255,255]*0.1), [1,1,3])}; 

基本上我們只着色那些細胞是i + j是偶數。

+0

剛剛添加了一個可以給棋盤的修改。第一塊代碼爲每個第二個像素着色,因此取決於您的高度是偶數還是奇數。新的代碼總是產生棋盤外觀 –

+0

嗨涅-mus,如果像素是白色的,只有像素灰色纔有可能?我有一個黑白圖像,我只想在白色部分有方格區域。我已經在我的原帖中發佈了一張示例圖片。 – user6029533

+0

@ user6029533我已經更新了此答案之上的答案,以包含初始像素應爲白色的情況。 – Suever

相關問題