使用 cv2 / pytesseract 进行数字识别的局部对比度增强

如何解决使用 cv2 / pytesseract 进行数字识别的局部对比度增强

我想使用 pytesseract 从图像中读取数字。图片如下:

enter image description here

enter image description here

数字是虚线,为了能够使用 pytesseract,我需要白色背景上的黑色连接数字。为此,我考虑使用 erodedilate 作为预处理技术。如您所见,图像相似,但在某些方面却大不相同。例如,第一个图像中的点比背景更暗,而第二个图像中的点更白。这意味着,在第一张图像中,我可以使用 erode 来获得黑色连接线,而在第二张图像中,我可以使用 dilate 来获得白色连接线,然后反转颜色。这导致以下结果:

enter image description here

enter image description here

使用适当的阈值,可以使用 pytesseract 轻松读取第一张图像。第二张图,不管是谁,都比较棘手。问题是,例如“4”的部分比三个周围的背景更暗。所以一个简单的阈值是行不通的。我需要诸如局部阈值或局部对比度增强之类的东西。这里有人有想法吗?

编辑:

OTSU、均值阈值和高斯阈值导致以下结果:

enter image description here

解决方法

您的图像分辨率很低,但您可以尝试一种称为增益划分的方法。这个想法是您尝试构建背景模型,然后通过该模型对每个输入像素进行加权。在大部分图像中,输出增益应该是相对恒定的。

进行增益分割后,您可以尝试通过应用区域过滤器形态学来改善图像。我只试过你的第一张图片,因为它是“最差的”。

这些是获取增益分割图像的步骤:

  1. 应用柔和的中值模糊过滤器以去除高频噪声。
  2. 通过局部最大值获取背景模型。应用一个非常强大的 close 操作,带有一个大 structuring element(我使用的是大小为 15 的矩形核)。
  3. 通过在每个局部最大像素之间划分 255 来执行增益调整。用每个输入图像像素加权这个值。
  4. 您应该得到一张漂亮的图像,其中背景照明几乎归一化threshold 此图像以获得字符的二进制掩码。

现在,您可以通过以下附加步骤提高图像质量:

  1. Threshold 通过 Otsu,但添加一点偏见。 (不幸的是,这是一个手动步骤,具体取决于输入)。

  2. 应用区域过滤器来过滤掉较小的噪声斑点。

让我们看看代码:

import numpy as np
import cv2

# image path
path = "C:/opencvImages/"
fileName = "iA904.png"

# Reading an image in default mode:
inputImage = cv2.imread(path+fileName)

# Remove small noise via median:
filterSize = 5
imageMedian = cv2.medianBlur(inputImage,filterSize)

# Get local maximum:
kernelSize = 15
maxKernel = cv2.getStructuringElement(cv2.MORPH_RECT,(kernelSize,kernelSize))
localMax = cv2.morphologyEx(imageMedian,cv2.MORPH_CLOSE,maxKernel,None,1,cv2.BORDER_REFLECT101)

# Perform gain division
gainDivision = np.where(localMax == 0,(inputImage/localMax))

# Clip the values to [0,255]
gainDivision = np.clip((255 * gainDivision),255)

# Convert the mat type from float to uint8:
gainDivision = gainDivision.astype("uint8") 

# Convert RGB to grayscale:
grayscaleImage = cv2.cvtColor(gainDivision,cv2.COLOR_BGR2GRAY)

这就是增益划分为您带来的好处:

请注意,照明更加平衡。现在,让我们应用一点对比度增强:

# Contrast Enhancement:
grayscaleImage = np.uint8(cv2.normalize(grayscaleImage,grayscaleImage,255,cv2.NORM_MINMAX))

你明白了,这会在前景和背景之间产生更多的对比:

现在,让我们尝试对这个图像设置阈值以获得一个漂亮的二进制掩码。正如我所建议的,尝试 Otsu 的阈值,但对结果添加(或减去)一点偏差。如前所述,此步骤取决于您输入的质量:

# Threshold via Otsu + bias adjustment:
threshValue,binaryImage = cv2.threshold(grayscaleImage,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

threshValue = 0.9 * threshValue
_,threshValue,cv2.THRESH_BINARY)

你最终得到这个二进制掩码:

反转它并过滤掉小斑点。我设置了 area 像素的 10 阈值:

# Invert image:
binaryImage = 255 - binaryImage

# Perform an area filter on the binary blobs:
componentsNumber,labeledImage,componentStats,componentCentroids = \
cv2.connectedComponentsWithStats(binaryImage,connectivity=4)

# Set the minimum pixels for the area filter:
minArea = 10

# Get the indices/labels of the remaining components based on the area stat
# (skip the background component at index 0)
remainingComponentLabels = [i for i in range(1,componentsNumber) if componentStats[i][4] >= minArea]

# Filter the labeled pixels based on the remaining labels,# assign pixel intensity to 255 (uint8) for the remaining pixels
filteredImage = np.where(np.isin(labeledImage,remainingComponentLabels) == True,0).astype("uint8")

这是最终的二进制掩码:

如果您打算将此图像发送到 OCR,您可能需要先应用一些形态。也许 closing 尝试加入组成字符的点。还要确保使用与您实际尝试识别的字体接近的字体来训练您的 OCR 分类器。这是大小 3 rectangular closing 操作和 3 次迭代后的(反转)掩码:

编辑:

要获得最后一张图片,请按如下方式处理过滤后的输出:

# Set kernel (structuring element) size:
kernelSize = 3

# Set operation iterations:
opIterations = 3

# Get the structuring element:
maxKernel = cv2.getStructuringElement(cv2.MORPH_RECT,kernelSize))

# Perform closing:
closingImage = cv2.morphologyEx(filteredImage,opIterations,cv2.BORDER_REFLECT101)

# Invert image to obtain black numbers on white background:
closingImage = 255 - closingImage

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-