最近在做人脸识别清洗样本的工作,发现经过人脸对齐后存在部分图片十分模糊,所以用opencv滤了一下。
原理就是使用了cv2.Laplacian()这个方法,代码如下。图片越模糊,imageVar的值越小,图像越模糊。
#-*-coding:utf-8-*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import cv2
import shutil
THRESHOLD = 30.0
dst_root = r'/media/unionpay/0009FFAB000A9861/CASIA&KFZX_CLEAR'
for fpath, dirs, fs in os.walk('/media/unionpay/0009FFAB000A9861/CASIA&KFZX'):
i = 0
for dir in dirs:
i += 1
if i%100 == 0:
print (str(i)+'folders processed current:'+dir)
abs_dir = os.path.join(fpath, dir)
for _, __, fs in os.walk(abs_dir):
clear_img_list = []
for f in fs:
item = os.path.join(_, f)
image = cv2.imread(os.path.join("/media/unionpay/0009FFAB000A9861/CASIA&KFZX/0000447", item))
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
imageVar = cv2.Laplacian(gray, cv2.CV_64F).var()
if not imageVar < THRESHOLD:
clear_img_list.append(item)
dst_folder = os.path.join(dst_root, dir)
if len(clear_img_list) >= 15:
if not os.path.exists(dst_folder):
os.mkdir(dst_folder)
for item in clear_img_list:
dst_path = os.path.join(dst_folder, item.split('/')[-1])
shutil.copy(item, dst_path)