python 判断图片是否以黑色或白色为主
展开阅读全文

python 判断图片是否以黑色或白色为主。占据图片大部分内容

python 筛选掉图片内容白色和黑色居多的图片

import os
from PIL import Image
import numpy as np

def is_too_black_or_white(image_path, black_threshold=0.4, white_threshold=0.4):
    """
    判断图片是否以黑色或白色为主。
    
    Args:
        image_path (str): 图片路径。
        black_threshold (float): 黑色像素比例阈值。
        white_threshold (float): 白色像素比例阈值。
        
    Returns:
        bool: 如果图片以黑色或白色为主,返回True;否则返回False。
    """
    # 打开图片并转换为灰度图
    image = Image.open(image_path).convert('L')
    pixels = np.array(image)

    # 计算黑色(像素值接近0)和白色(像素值接近255)像素的比例
    black_pixels = np.sum(pixels <= 30) / pixels.size  # 阈值30可根据需要调整
    white_pixels = np.sum(pixels >= 225) / pixels.size  # 阈值225可根据需要调整

    # 判断是否以黑色或白色为主
    return black_pixels > black_threshold or white_pixels > white_threshold

def filter_images(directory, output_directory, black_threshold=0.4, white_threshold=0.4):
    """
    遍历目录,筛选出不是以黑色或白色为主的图片,并保存到输出目录。
    
    Args:
        directory (str): 输入图片目录。
        output_directory (str): 输出目录。
        black_threshold (float): 黑色像素比例阈值。
        white_threshold (float): 白色像素比例阈值。
    """
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    for filename in os.listdir(directory):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):
            image_path = os.path.join(directory, filename)
            if not is_too_black_or_white(image_path, black_threshold, white_threshold):
                output_path = os.path.join(output_directory, filename)
                # 复制图片到输出目录
                with open(image_path, 'rb') as f_in, open(output_path, 'wb') as f_out:
                    f_out.write(f_in.read())

# 示例使用
input_dir = 'path/to/your/input/directory'
output_dir = 'path/to/your/output/directory'
filter_images(input_dir, output_dir)