```python
# -*- coding: utf-8 -*-
"""指定目录的图片,自适应2值化
"""
import os
from PIL import Image
import numpy as np
import glob
def avgGray(img):
"""计算灰度图像平均灰度值,方差"""
im_gray1 = np.array(img)
avg_gray = np.average(im_gray1)
return np.round(avg_gray, 0), np.round(np.std(img), 0)
def maxMinGray(img):
"""计算灰度图像最大、最小灰度值"""
im_gray1 = np.array(img)
return np.round(np.max(im_gray1), 0), np.round(np.min(im_gray1), 0)
def translate(filename="test.jpg", saveToPath="/tmp"):
"""将图片保存为二值"""
img = Image.open(filename)
# 模式L”为灰色图像,它的每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度。
Img = img.convert('L')
# 保存灰度图
# Img.save(os.path.join(saveToPath, "tmpqwerty.jpg"))
# 自定义灰度界限,大于这个值为黑色,小于这个值为白色
threshold = 150
# 灰度平均值,方差
avggray, std = avgGray(img)
# threshold = avgGray(img) * 1.3
threshold = avggray - 2 * std if avggray > 127 else avggray + 2 * std
# threshold = avggray - 1 * std if avggray > 127 else avggray + 1 * std
# threshold = avggray - 2.5 * std if avggray > 127 else avggray + 2.5 * std
print(f"灰度平均值,方差:{avgGray(img)},灰度界限:{threshold} ;最大、最小灰度值:{maxMinGray(img)}")
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
# 图片二值化
photo = Img.point(table, '1')
saveToFile = os.path.join(saveToPath, os.path.basename(filename))
print(f"save to file : {saveToFile}")
photo.save(saveToFile)
def main():
image_list = []
for filename in glob.glob(os.path.join(picpath, '*.jpg')): # assuming jpg
# im=Image.open(filename)
image_list.append(filename)
for i in range(len(image_list)):
translate(image_list[i])
if __name__ == "__main__":
# 需要处理的图片路径;
picpath = "/dev/shm/temp/"
main()
```