Files
zjsh_yolov11/image/del_photo/change.py
2025-09-01 14:14:18 +08:00

90 lines
3.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
from PIL import Image
import numpy as np
def is_large_gray(image, gray_lower_threshold=70, gray_upper_threshold=230, gray_ratio_threshold=0.7):
"""
判断图片是否大面积为灰色(基于像素的颜色值)
参数:
- image: 图片对象PIL Image
- gray_lower_threshold: 灰色下限(低于此值不算“灰色”)
- gray_upper_threshold: 灰色上限(高于此值不算“灰色”)
- gray_ratio_threshold: 灰色像素占比阈值(>70% 算大面积灰色)
返回True 表示是大面积灰色,应删除
"""
# 将图片转换为 numpy 数组
img_array = np.array(image)
# 获取图片的尺寸
height, width, _ = img_array.shape
total_pixels = height * width
# 判断是否为灰色像素R、G、B 值都在 gray_lower_threshold 和 gray_upper_threshold 之间)
gray_pixels = np.sum(
(img_array[:, :, 0] >= gray_lower_threshold) &
(img_array[:, :, 0] <= gray_upper_threshold) &
(img_array[:, :, 1] >= gray_lower_threshold) &
(img_array[:, :, 1] <= gray_upper_threshold) &
(img_array[:, :, 2] >= gray_lower_threshold) &
(img_array[:, :, 2] <= gray_upper_threshold)
)
gray_ratio = gray_pixels / total_pixels
return gray_ratio > gray_ratio_threshold
def process_images_in_folder(input_folder, output_folder):
"""
遍历文件夹,旋转图片并根据条件保存到输出文件夹
"""
# 创建输出文件夹(如果不存在)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 支持的图片格式
supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.tif', '.webp')
for filename in os.listdir(input_folder):
file_path = os.path.join(input_folder, filename)
if not os.path.isfile(file_path):
continue
if not filename.lower().endswith(supported_formats):
continue
print(f"处理: {filename}")
try:
with Image.open(file_path) as img:
# 判断是否为大面积灰色
if is_large_gray(img):
print(f" 🔴 不保存大面积灰色图片: {filename}")
continue # 不保存该图片
# 否则:打开并旋转 180 度
rotated_img = img.rotate(180, expand=False)
# 构建新的保存路径
save_path = os.path.join(output_folder, filename)
# 保持原格式保存(覆盖原图)
rotated_img.save(save_path, format=img.format)
print(f" ✅ 已旋转并保存至: {save_path}")
except Exception as e:
print(f" ❌ 处理失败 {filename}: {e}")
# ================ 使用示例 ================
if __name__ == "__main__":
folder = "/media/hx/04e879fa-d697-4b02-ac7e-a4148876ebb0/dataset/f15"
output_folder = "/media/hx/04e879fa-d697-4b02-ac7e-a4148876ebb0/dataset/f15"
if not os.path.exists(folder):
print("❌ 输入文件夹不存在!")
else:
process_images_in_folder(folder, output_folder)
print("✅ 所有图片处理完成!")