【问题标题】:Simplifying an image in matlab在matlab中简化图像
【发布时间】:2023-06-11 06:31:01
【问题描述】:

我有一张手写字母的图片(比如字母“y”)。只保留三个颜色值中的第一个(因为它是灰度图像),我得到一个 111x81 矩阵,我称之为 aLetter。我可以通过以下方式看到这张图片(请忽略标题):

颜色图灰色; image(aLetter,'CDataMapping','缩放')

我想要的是删除这个字母周围的空白并以某种方式平均剩余的像素,以便我有一个 8x8 矩阵(我们称之为 simpleALetter)。现在如果我使用:

颜色图灰色; image(simpleALetter,'CDataMapping','scaled')

我应该看到这封信的像素化版本:

任何关于如何做到这一点的建议将不胜感激!

【问题讨论】:

    标签: image matlab


    【解决方案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% 的图像是“白色”,您可以通过对像素进行排序并动态查找阈值来确定正确的阈值 - 正如我在代码中的评论中提到的那样“玩它”,直到你找到适合你情况的东西。

    【讨论】:

    • 代码似乎将白色背景视为非零。
    • @rwong - 你可能是对的。我来自“white = 0”的背景,但如果“white = 1”则需要反转前几行的逻辑。
    • 白色背景的值为 255
    • 如果您已经拥有 Image Processing Toolbox,则可以使用 imresize 完成最后的重采样步骤。
    • 谢谢你们两位。有没有办法让我也感谢 rwong 并给他业力点或其他东西(不完全熟悉这个网站)? aLetter(aLetter