python检测“无内容”图片

思路1:通过图像熵检测,“无内容”图像熵较小,可通过设置阈值检测“无内容”图像,计算图像熵可参考:https://www.cnblogs.com/niulang/p/12195152.html

思路2:检测图像中连通区域个数和面积

思路2代码:

import cv2
import numpy as np
import math
import time
import os
import shutil

def get_cell_cnt(img_):
    x, y = img_.shape[0:2]
    img_ = cv2.resize(img_, (int(y/4), int(x/4)))
    ret, binary = cv2.threshold(img_, 95, 255, cv2.THRESH_BINARY)
    cv2.imwrite(path + 'abc.png', binary)
    kernel_1 = np.ones((3,3),np.uint8) # 定义核
    opening = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel_1)
    cv2.imwrite(path + 'abc_1.png', opening)
    opening_x = opening.shape[0]
    opening_y = opening.shape[1]
    opening[:,0] = 255
    opening[:,opening_y-1] = 255
    opening[0,:] = 255
    opening[opening_x-1,:] = 255
    # 检测图像连通区(输入为二值化图像)
    image, contours, hierarchy = cv2.findContours(opening,1,2) # 检测连通区域
    sign = 0
    for n in range(len(contours)):
        cnt = contours[n]
        area = cv2.contourArea(cnt)
        if area > 12:
            sign = sign + 1
 #   cv2.imwrite(path + 'abc_open.png', opening)
 #   cv2.imwrite(path + 'abc_close_range.png', img_)
    return sign
for path_ in open('list.txt'):
    t1 = time.time()
    path = path_[:-1]
    image = cv2.imread(path,0)
    t2 = time.time()
    cell_cnt = get_cell_cnt(image)
    t3 = time.time()
    if cell_cnt < 2:
        newpath = os.path.join('copy', path.split('/')[1])
        shutil.copy(path, newpath)
    print('time',t2-t1,t3-t1)

  

原文地址:https://www.cnblogs.com/niulang/p/12197201.html