python检测空白文档(无内容)图片

# coding: utf-8
#python检测“无内容”图片
#通过图像熵检测,无内容图像熵较小,可通过设置阈值检测无内容图像
import cv2
import numpy as np
import math
import time
import os
import shutil
def get_entropy(img_):
    x, y = img_.shape[0:2]
    img_ = cv2.resize(img_, (100, 100)) # 缩小的目的是加快计算速度
    tmp = []
    for i in range(256):
        tmp.append(0)
    val = 0
    k = 0
    res = 0
    img = np.array(img_)
    for i in range(len(img)):
        for j in range(len(img[i])):
            val = img[i][j]
            tmp[val] = float(tmp[val] + 1)
            k =  float(k + 1)
    for i in range(len(tmp)):
        tmp[i] = float(tmp[i] / k)
    for i in range(len(tmp)):
        if(tmp[i] == 0):
            res = res
        else:
            res = float(res - tmp[i] * (math.log(tmp[i]) / math.log(2.0)))
    return res

original_path=r"C:\study_he\exp_result\test"#原始图片
kongbai_path=r"C:\study_he\exp_result\result"#存放无内容的图片
for file in os.listdir(original_path):
    original_img=os.path.join(original_path,file)
    original = cv2.imread(original_img,0)
    res = get_entropy(original)
    print(res)
    #根据经验设的阈值,可根据需要修改
    if res<4:
        print(original_img)
        shutil.move(original_img,os.path.join(kongbai_path,file))


原始图像:
python检测空白文档(无内容)图片_第1张图片
程序运行之后的结果:
python检测空白文档(无内容)图片_第2张图片
python检测空白文档(无内容)图片_第3张图片

你可能感兴趣的:(python检测空白文档(无内容)图片)