批量修改身份证扫描件
@功能1:实现了OCR图像识别
@功能2:实现了文件的重命名
-
实际演示效果(本文章仅用于学习参考)
运行状态.png
实测效果.png
@_@: 代码写的比较烂希望大佬指出不足!!!
# -*- encoding: utf-8 -*-
"""
@File : ID card.py
@Contact : t.ianxi@foxmail.com
@License : // Copyright (C) 2018 Milo Yip<dell>
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2022/8/18 9:45 MuKe~ 1.0 None
"""
import os
import time
import pytesseract
from PIL import Image
from tqdm import tqdm
def Im_crop(Tup_path):
"""
历遍目录、获取路径、裁剪姓名、身份证号
:param Tup_path:图片路径
:return:
"""
# 历遍目录
for i,i1,i2 in os.walk(Tup_path,topdown=True):
list_name = i2
# 输出图片信息
print("[INFO]",i2)
# 统计当前路径下共多少张图片
Num_files = len(os.listdir(Tup_path))
# 历遍图片
for i in range(Num_files):
# 打开图片
im = Image.open(Tup_path+"\\"+list_name[i])
# 裁剪姓名
im_Name = im.crop((1196,1201,1449,1340))
# 裁剪身份证号码
im_ID = im.crop((1389,1786,2259,1972))
# im_ID.show()
# 拼接图片路径(为重命名使用)
path_img = Tup_path+"\\"+list_name[i]
# 调用自定义函数
OCR_txt(im_Name,im_ID,path_img)
def OCR_txt(im_Name,im_ID,path_img):
"""
对图片进行处理、图像转灰度
:param im_Name: 姓名
:param im_ID: 身份证号码
:param path_img: 图片路径
:return:
"""
# 使用img对象的convert()方法传入参数L,即可将图片转换为灰度图像
im_Name_img = im_Name.convert('L')
# 定义一个二值化的阈值(默认值127) 注意:处理图像时必须现将图像转换为灰度图像
threshold = 136
# 创建一个空列表用于存储二值化阈值
table = []
# 历遍阈值i表示历遍到的阈值
for i in range(256):
if i < threshold:
# 如果数值大于设定的阈值,则添加向列表中添加0
table.append(0)
else:
# 如果数值小于设定的阈值,则添加向列表中添加1
table.append(1)
# img对象的point()方法,作用是通过查找表或函数映射此图像。参数讲解参考文章:https://vimsky.com/examples/usage/python-pil-image-point-method.html
im_Name_img = im_Name_img.point(table, '1')
# 调用show()函数打开图片显示
im_Name_img.show()
# 调用pytesseract库的image_to_string()方法来识别姓名截图参数【图片,语言】lang='chi_sim'中文语言
Name = pytesseract.image_to_string(im_Name_img, lang='chi_sim')
# 调用pytesseract库的image_to_string()方法来识别身份证截图参数【图片,语言】lang='eng'英文语言
Id = pytesseract.image_to_string(im_ID, lang='eng')
# 调用自定义函数
files(path_img,Id,Name)
def files(path_img,Id,Name):
"""
对文件检测是否存在、对图片重命名、输出内容
:param path_img:图片路径
:param Id:身份证号码
:param Name:姓名
:return:
"""
# 判断图片是否存在
if os.path.exists(path_img):
# rename()方法使用重命名.replace()函数替换身份证中识别错误导致的“/” 起过滤作用 strip()函数也是
os.rename(path_img,Tup_path+"\\"+Id.replace('/',"").strip('\n').strip('\t').strip('\r').strip('/')+".jpg")
print("姓名:{Name} 身份证号码:{Id}".format(Name=Name,Id=Id))
# 图片路径
Tup_path = r"E:\2022近期工作\户籍\原始文件"
# 创建main(程序入口)
if __name__=='__main__':
# 实例化自定义函数
Im_crop(Tup_path)

