我有一些图片,其中包含一个带数字的字符串,例如:“我们有3本书”。 我需要获取数字3: 是否有Java库可以读取图像并提取数字?或者可能先解析该字符串以查找数字?
谢谢
我有一些图片,其中包含一个带数字的字符串,例如:“我们有3本书”。 我需要获取数字3: 是否有Java库可以读取图像并提取数字?或者可能先解析该字符串以查找数字?
谢谢
使用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);
}
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
}