你需要幾個步驟來實現你想要的(更新中的@ rwong的觀察光,我有白色和黑色翻轉...):
- 求信的大致「邊框」:
- 確保「文本」是圖像
- 組的東西都是「不文」零的最高值 - 下面沿行和列的閾
- 總和東西,發現非零像素
- 上採樣的邊框,以8
- 下采樣的多個圖像,以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%是「白色」,你可以通過排序像素和動態查找閾值來確定正確的閾值 - 正如我在代碼「隨它玩」,直到找到適合你的情況的東西。
該代碼似乎將白色背景視爲非零。 – rwong
@rwong - 你可能是對的。我來自「白色= 0」的背景,但如果「白色= 1」,則需要反轉前幾行的邏輯。 – Floris
白色背景的值爲255 – ilikecats