python图像签名背景消除
利用python的PIL库可以进行图像的二值化,从而将图像的背景删除,可以参考https://blog.csdn.net/qq_16669583/article/details/106318056?ivk_sa=1024320u博主的文章,我又加了一个自动筛选、批量处理的功能。
#coding:utf-8
from PIL import Image
from PIL import ImageOps
import os
import re
def initTable(threshold=200):
# 阈值可调,我的图片在PPT中做过图像更正,所以阈值较大。
table = []
for i in range(256):
if i < threshold:
table.append(1)
else:
table.append(0)
return table
def Search_File(dirname,suffix):
'''
This function can search all files with the specified suffix in this dir.
:param dirname: string, the path need to be searched
:param suffix: string, the specified suffix need to be seached
:return:
filter_list: list, the path list need to be searched.
'''
filter = [suffix] # 设置过滤后的文件类型 当然可以设置多个类型
filter_list = []
for maindir, subdir, file_name_list in os.walk(dirname):
#print(maindir) #当前主目录
for filename in file_name_list:
apath = os.path.join(maindir, filename)#合并成一个完整路径
portion = os.path.splitext(apath)
ext = portion[1] # 获取文件后缀 [0]获取的是除了文件名以外的内容
if ext in filter:
newname = portion[0] + suffix
filter_list.append((newname,portion[0].split("\\")[-1]))
return filter_list
if __name__ == "__main__":
for i,n in Search_File(r"C:\Users\Think\Desktop\新建文件夹 (4)",".png"):
# 直接输入文件所在的文件夹路径和图片格式即可
print(i)
image = Image.open(i)
# 转化为二值图片
imgry = image.convert('L')
# 根据阈值将图片的二值化像素值转化为0和1,理论上只需将签名的像素设为0,其它背景设为1
binary = imgry.point(initTable(), '1')
# 再次进行二值化
im1 = binary.convert('L')
im2 = ImageOps.invert(im1)
im3 = im2.convert('1')
im4 = im3.convert('L')
# 输入保存路径,需要保存在和原始文件不同的路径下
im4.save(r"C:\Users\Think\Desktop\新建文件夹 (4)\新建文件夹\{}".format(n+".png"))