python ocr识别图片中的文字前,怎么对图片进行白底黑字处理
可以使用Python中的PIL库(Pillow库的一种分支)来实现对图片的处理。
具体步骤如下:
- 使用PIL库中的Image模块打开原始图片
from PIL import Image
img = Image.open('original_image.png')
- 将原始图片转换为灰度图
gray_img = img.convert('L')
- 对灰度图进行二值化处理,将灰度值大于某个阈值的像素点设为白色,其余像素点设为黑色。可以使用PIL库中的ImageOps模块的invert和threshold方法来实现。
from PIL import ImageOps
# 将灰度图反转,变为白底黑字
inverted_img = ImageOps.invert(gray_img)
# 将反转后的灰度图进行二值化处理,阈值为100
threshold_img = inverted_img.convert('1', threshold=100)
- 对处理后的图片进行保存
threshold_img.save('processed_image.png')
完整代码如下:
from PIL import Image, ImageOps
# 打开原始图片
img = Image.open('original_image.png')
# 将原始图片转换为灰度图
gray_img = img.convert('L')
# 将灰度图反转,变为白底黑字
inverted_img = ImageOps.invert(gray_img)
# 将反转后的灰度图进行二值化处理,阈值为100
threshold_img = inverted_img.convert('1', threshold=100)
# 保存处理后的图片
threshold_img.save('processed_image.png')
原文地址: http://www.cveoy.top/t/topic/vS7 著作权归作者所有。请勿转载和采集!