处理不清晰的扫描件进行内部红章等检测时,往往需要增强图片进行检测,可以有效地提高得到地准确率和confidence。经实验表明,对比度增强和锐化往往能提高OCR、检测等精度。
from PIL import Image
from PIL import ImageEnhance
import numpy as np
import os
path = 'xxx'
for i in os.listdir(path):
p_ = path + i
img = Image.open(p_).convert('RGB')
img_gray = Image.open(p_).convert('L')
mean_gray = np.mean(img_gray)
w_old, h_old = img.size
min_wid = min(w_old, h_old)
throld_resize = xxx
if min_wid<throld_resize:
w_new, h_new = int(w_old/min_wid *throld_resize), int(h_old/min_wid *throld_resize)
img = img.resize((w_new, h_new))
if mean_gray>throld_resize :
""" #亮度增强
enh_bri = ImageEnhance.Brightness(img)
brightness = 1.0
image_brightened = enh_bri.enhance(brightness)
#色度增强
enh_col = ImageEnhance.Color(image_brightened)
color = 1.0
image_colored = enh_col.enhance(color) """
#对比度增强
enh_con = ImageEnhance.Contrast(img)
contrast = 2.5 #1.2
image_contrasted = enh_con.enhance(contrast)
#image_contrasted.show()
image_contrasted.save('xxxx')
#锐度增强
enh_sha = ImageEnhance.Sharpness(image_contrasted)
sharpness = 1.5 #2.5
image_sharped = enh_sha.enhance(sharpness)
#image_sharped.show()
image_sharped.save('xxxx')
img = image_sharped