使用Python筛选400×400尺寸上下含大量留白的横向图片
问题分析
原代码的核心缺陷在于:
- 仅检查上下5%的窄条区域,无法反映整体上下留白的真实占比
- 未区分有效内容的方向,也没有排除侧边留白过多的图片
- 阈值设置过低(0.2),导致大量非目标图片被误选
改进方案
我们需要先定位图片的有效内容区域,再通过内容区域的宽高比、上下留白占比、左右留白占比三个维度精准筛选目标图片:
from PIL import Image import os import shutil def is_target_horizontal_image(image_path, white_threshold=200, min_top_bottom_gap_ratio=0.3, max_side_gap_ratio=0.2): img = Image.open(image_path) width, height = img.size # 固定为400×400 # 转为灰度图,简化白色像素判断逻辑 gray_img = img.convert("L") pixel_data = gray_img.getdata() # 提取所有非白色像素的坐标(判断有效内容范围) non_white_coords = [idx for idx, val in enumerate(pixel_data) if val < white_threshold] if not non_white_coords: # 全白图片直接跳过 return False # 计算有效内容区域的上下左右边界 min_y = min(coord // width for coord in non_white_coords) max_y = max(coord // width for coord in non_white_coords) min_x = min(coord % width for coord in non_white_coords) max_x = max(coord % width for coord in non_white_coords) # 计算内容区域的宽高 content_width = max_x - min_x + 1 content_height = max_y - min_y + 1 # 条件1:有效内容为横向(宽度大于高度) if content_width <= content_height: return False # 条件2:上下留白总占比达标 total_top_bottom_gap = height - content_height top_bottom_gap_ratio = total_top_bottom_gap / height if top_bottom_gap_ratio < min_top_bottom_gap_ratio: return False # 条件3:左右留白占比不超标,排除侧边留白多的图片 total_side_gap = width - content_width side_gap_ratio = total_side_gap / width if side_gap_ratio > max_side_gap_ratio: return False return True def filter_target_images(input_folder, output_folder): os.makedirs(output_folder, exist_ok=True) image_extensions = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff') for filename in os.listdir(input_folder): if filename.lower().endswith(image_extensions): img_path = os.path.join(input_folder, filename) if is_target_horizontal_image(img_path): shutil.copy2(img_path, os.path.join(output_folder, filename)) if __name__ == "__main__": input_dir = r'your/input/folder/path' output_dir = r'your/output/folder/path' filter_target_images(input_dir, output_dir) print(f"筛选完成,结果已保存到: {output_dir}")
参数说明
white_threshold=200:判断白色像素的阈值,可根据图片实际白色深浅调整(数值越接近255判断越严格)min_top_bottom_gap_ratio=0.3:要求上下留白总占比至少30%,可按需提高或降低max_side_gap_ratio=0.2:限制左右留白总占比不超过20%,避免误选侧边留白多的纵向内容图片
内容的提问来源于stack exchange,提问作者Mycode
相关产品推荐
相关产品推荐

