2014-03-14 43 views
0

我有一張手寫字母的圖片(比如字母「y」)。只保留三個顏色值中的第一個(因爲它是一個灰度圖像),我得到一個111x81的矩陣,我稱之爲信函。我可以看到這張圖片(請忽略標題):在matlab中簡化圖像

colormap grey;圖像(880,「CDataMapping」,「縮放」)

Picture of handwritten letter

我想是消除圍繞這封信的空白,不知何故平均剩餘像素,這樣我有一個8×8矩陣(姑且稱之爲simpleALetter)。現在,如果我使用:

colormap grey;圖像(simpleALetter,「CDataMapping」,「縮放」)

我應該看到這封信的像素化版本:

pixellated version of the handwritten letter

如何做到這一點的任何建議,將不勝感激!

回答

1

你需要幾個步驟來實現你想要的(更新中的@ rwong的觀察光,我有白色和黑色翻轉...):

  1. 求信的大致「邊框」:
    • 確保「文本」是圖像
    • 組的東西都是「不文」零的最高值 - 下面沿行和列的閾
    • 總和東西,發現非零像素
  2. 上採樣的邊框,以8
  3. 下采樣的多個圖像,以8X8

這裏是你可能會怎麼做,以你的情況

aLetter = max(aLetter(:)) - aLetter; % invert image: now white = close to zero 
aLetter = aLetter - min(aLetter(:)); % make the smallest value zero 
maxA = max(aLetter(:)); 
aLetter(aLetter < 0.1 * maxA) = 0; % thresholding; play with this to set "white" to zero 

% find the bounding box: 
rowsum = sum(aLetter, 1); 
colsum = sum(aLetter, 2); 
nonzeroH = find(rowsum); 
nonzeroV = find(colsum); 
smallerLetter = aLetter(nonzeroV(1):nonzeroV(end), nonzeroH(1):nonzeroH(end)); 

% now we have the box, but it's not 8x8 yet. Resampling: 
sz = size(smallerLetter); 

% first upsample in both X and Y by a factor 8: 
bigLetter = repmat(reshape(smallerLetter, [1 sz(1) 1 sz(2)]), [8 1 8 1]); 
% then reshape and sum so you end up with 8x8 in the final matrix: 
letter8 = squeeze(sum(sum(reshape(bigLetter, [sz(1) 8 sz(2) 8]), 3), 1)); 

% finally, flip it back "the right way" black is black and white is white: 
letter8 = 255 - (letter8 * 255/max(letter8(:))); 

你可以這樣做明確的for循環,但它會慢得多。

您也可以在Matlab中使用一些blockproc函數,但我今晚使用的是Freemat,它沒有這些...它也沒有任何圖像處理工具箱的功能,所以這是「硬核」。

至於選擇一個好的閾值:如果你知道你的圖像> 90%是「白色」,你可以通過排序像素和動態查找閾值來確定正確的閾值 - 正如我在代碼「隨它玩」,直到找到適合你的情況的東西。

+0

該代碼似乎將白色背景視爲非零。 – rwong

+0

@rwong - 你可能是對的。我來自「白色= 0」的背景,但如果「白色= 1」,則需要反轉前幾行的邏輯。 – Floris

+0

白色背景的值爲255 – ilikecats