Python图片二值化原理与代码实现
本文分享一种基于Python的图片二值化处理方法,旨在通过预处理提升后续文字识别的准确率。文中提供了详细的代码实现与效果对比,为相关开发工作提供实用的参考方案。
具体实现逻辑如下所示。
import cv2from PIL import Imagefrom pytesseract import pytesseractfrom PIL import ImageEnhanceimport reimport string
def createFile(filePath,newFilePath):
img = Image.open(filePath)
# 模式L”为灰色图像,它的每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度。
Img = img.convert('L')
Img.save(newFilePath)
# 自定义灰度界限,大于这个值为黑色,小于这个值为白色
threshold = 200
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
# 图片二值化
photo = Img.point(table, '1')
photo.save(newFilePath)
if __name__ == '__main__':
createFile(r'1.bmp',r'newTest.png')
处理前的原始图像文件。

经过二值化算法处理后的图像结果。

对处理后图像进行识别所得到的文本输出。

以上内容涵盖了图片二值化的核心代码与流程,希望能为读者的学习与项目实践带来帮助。