2014-03-14 42 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