如何从图片中识别数字?

3

我有一些图片,其中包含一个带数字的字符串,例如:“我们有3本书”。 我需要获取数字3: 是否有Java库可以读取图像并提取数字?或者可能先解析该字符串以查找数字?

谢谢


3
可能是Java OCR实现的重复问题。 - Marc B
3个回答

5

2

使用tess4j,你可以尝试以下方法:

public static void main(final String[] args) throws Exception {
    final File imageFile = new File("imageWith Digits.jpg");
    final ITesseract instance = new Tesseract();
    instance.setTessVariable("tessedit_char_whitelist", "0123456789");
    final String result = instance.doOCR(imageFile);
    System.out.println(result);
}

1

Tess4J是一个很好的工具,我试过版本4.5.5和官方仓库中的tessdata: https://github.com/nguyenq/tess4j

需要注意的是它不能处理jpg和tif格式,但png格式完美支持。 我有一个简单的案例,黑底白字。

我搜索了一段时间,没有找到快速解决方案。因此,即使这篇文章有点旧,我的评论也可能会帮助那些在图像上寻找简单数字识别的人。

有人建议我用一些代码片段来改进我的回答。因此,建议将图像二值化以获得更好的文本和数字识别结果。可以使用这个简单的计算,它使用java.awt.image.BufferedImage编写的Kotlin代码:

    fun binarize(img: BufferedImage): BufferedImage {
        val bufferedImage = BufferedImage(img.width, img.height, BufferedImage.TYPE_INT_RGB)
        for (i in 0 until img.width) {
            for (j in 0 until img.height) {
                val rgbValues: Int = img.getRGB(i, j)
                //An int can be represented with 8 hex numbers. The first two are the alpha value, 
                // which we will ignore within this calculation followed by two hex numbers for red, 
                // two for green and two for blue 
                val r = 0x00ff0000 and rgbValues shr 16
                val g = 0x0000ff00 and rgbValues shr 8
                val b = 0x000000ff and rgbValues
                val m = r + g + b
                //(255+255+255)/2 = 383 middle of dark and light
                bufferedImage.setRGB(i, j, if (m >= 383) Color.WHITE.rgb else 0)
            }
        }
        return bufferedImage
    }

这里发生的是,我们对每个像素的红色、绿色和蓝色值进行求和,并除以2。当结果小于383时,我们将该像素设为黑色,否则设为白色。因此,我们得到了一个仅有黑色和白色像素的新图像,然后将其返回。
要查看完整示例,请参见:https://github.com/pachecoberlin/screenshotter

Tess4J已经被另一个答案提到了。为了改进你的回答,请提供一些代码片段。谢谢! - sanastasiadis
实际上,Hilmar 的回答非常好,我想发表评论,但还没有足够的声望来这样做。无论如何,我将添加一个简单的二值化方法,可能会提供更好的结果。 - Pacheco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接