你需要几个步骤来实现你想要的(更新中的@ 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