我正在尝试区分文本文档的图像和其他非文本文档的图像。我希望编写一个方法,如果图像是文档的图像,则返回DOCUMENT
,如果不是文档的图像,则返回IMAGE
。
文本文档的示例图像
非文本文档的示例图像
有什么方法可以做到这一点吗?我应该使用霍夫线变换来查看图像中是否有直的水平线吗?
我正在考虑的方法
- 对图像进行霍夫变换。只考虑水平线。如果水平线太多(一些预定义的阈值),那么我可以说这是一个文本文档的图像
- 检测图像中是否有很多黑色文本在白色背景上。这样我可以相当有信心地说这是一个文本文档的图像。(不过我不确定如何做到这一点)
回答:
这里有一些想法 – 用ImageMagick表达,但很容易适应OpenCV。ImageMagick安装在大多数Linux发行版中,并且可用于OSX和Windows,如果你不幸被迫使用Windows的话。
建议1 – 初始质量
第一个建议是尽量以PNG格式而不是JPEG格式获取屏幕截图 – 对于任何严肃的处理来说,PNG格式要好得多。
建议2 – 裁剪无关内容
其次,由于你有很多多余的无关内容,包括PDF查看器的框架,我建议在进行任何处理之前先裁剪图像的中间部分,这样可以去除大部分无关内容,并且对检测文本行不会有太大影响,因为文本行在页面中间很可能是一样的。也就是说:
convert textual.jpg -gravity center -crop 70x70% x.png
建议3 – 白色像素百分比
接下来,查看白色像素的百分比,如果是文本图像,寻找高数值,如果是非文本图像,寻找低数值:
# 检查白色空间百分比convert textual.jpg -gravity center -crop 70x70% -normalize -threshold 90% -format "%[fx:int(mean*100)]\n" info:90convert nontextual.jpg -gravity center -crop 70x70% -normalize -threshold 90% -format "%[fx:int(mean*100)]\n" info:8
建议4 – 寻找交替的黑白行
接下来,尝试将图像扭曲至1像素宽,与原始图像相同的高度,然后对其进行阈值处理。然后计算黑白之间的交替次数 – 文本图像很多,非文本图像很少:
# 检查交替的黑白水平线convert textual.jpg -gravity center -crop 70x70% -threshold 50% -resize 1x! -normalize -threshold 95% -scale 20x! result.png
而对于非文本图像:
# 检查交替的黑白水平线convert nontextual.jpg -gravity center -crop 70x70% -threshold 50% -resize 1x! -normalize -threshold 95% -scale 20x! result.png
建议5 – 连通组件分析
最后,我会考虑进行“连通组件分析”或“斑点分析”。对于文本图像,你会得到很多小的、水平对齐的斑点 – 对应于单词或字母 – 这取决于你原始屏幕截图的质量。
对于文本图像:
convert textual.jpg -gravity center -crop 70x70% \ -colorspace gray -negate -threshold 10% \ -define connected-components:verbose=true \ -define connected-components:area-threshold=0 \ -connected-components 8 -auto-level output.png
输出 – 1300个对象
Objects (id: bounding-box centroid area mean-color): 88: 768x627+0+18 387.5,315.7 436659 srgb(0,0,0) 0: 768x18+0+0 387.6,9.2 12194 srgb(255,255,255) 28: 118x7+408+0 466.1,2.8 709 srgb(0,0,0) 354: 78x16+125+428 164.8,435.3 466 srgb(255,255,255) 1184: 76x16+146+629 185.1,636.7 417 srgb(255,255,255) 158: 28x35+358+250 371.5,265.9 411 srgb(255,255,255) ... ... 14: 1x1+201+0 201.0,0.0 1 srgb(0,0,0) 346: 1x1+456+419 456.0,419.0 1 srgb(255,255,255) 347: 1x1+46+423 46.0,423.0 1 srgb(255,255,255) 183: 1x1+126+274 126.0,274.0 1 srgb(0,0,0)
显示找到的对象的标记输出图像 – 每个对象的阴影依次变浅(1300种阴影):
而对于非文本图像:
convert nontextual.jpg -gravity center -crop 70x70% \ -colorspace gray -negate -threshold 10% \ -define connected-components:verbose=true \ -define connected-components:area-threshold=0 \ -connected-components 8 -auto-level output.png
输出 – 57个对象
Objects (id: bounding-box centroid area mean-color): 1: 315x237+0+0 153.6,115.2 68351 srgb(255,255,255) 22: 56x147+181+42 215.4,119.3 3768 srgb(0,0,0) 35: 23x10+106+227 117.0,232.0 184 srgb(0,0,0) 36: 23x10+179+227 189.9,231.9 183 srgb(0,0,0) 38: 22x10+264+227 274.5,231.9 179 srgb(0,0,0) 37: 22x10+230+227 240.7,231.9 178 srgb(0,0,0) ... ... 24: 1x1+200+50 200.0,50.0 1 srgb(0,0,0) 25: 1x1+216+57 216.0,57.0 1 srgb(0,0,0) 26: 1x1+220+61 220.0,61.0 1 srgb(0,0,0)
显示找到的对象的标记输出图像 – 每个对象的阴影依次变浅,你可以看到阴影较少(只有57种):