手机照片整理:AI批量删除模糊图片和没有人像的图片

部落人有文化 2024-07-15 13:28:42

电脑中有上万张手机照片要整理,比如删除掉模糊的图片,删除掉没有人像的图片,手动整理会累坏的。这种苦差事交给AI办就好了。

在ChatGPT中输入提示词:

写一个Python脚本,完成批量删除模糊图片和没有人像的图片的任务,具体步骤如下;

打开文件夹:F:\aivideo

读取里面所有的图片;

使用OpenCV来检测和删除模糊图像;

用TensorFlow和预训练的模型MTCNN来检测和删除不包含人像的图片;

注意:每一步都要输出信息到屏幕上

首先确保安装了所需的库:

pip install opencv-python-headless pillow mtcnn tensorflow

源代码:

import cv2

import os

import numpy as np

from mtcnn import MTCNN

# Function to check if an image is blurry

def is_blurry(image_path, threshold=100):

image = cv2.imread(image_path)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

laplacian_var = cv2.Laplacian(gray, cv2.CV_64F).var()

return laplacian_var < threshold

# Function to check if an image contains a face using MTCNN

def has_face(image_path):

detector = MTCNN()

image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)

faces = detector.detect_faces(image)

return len(faces) > 0

# Function to process images in a directory

def process_images(directory):

if not os.path.exists(directory):

print(f"Directory {directory} does not exist.")

return

print(f"Processing images in directory: {directory}")

total_images = 0

deleted_blurry = 0

deleted_no_face = 0

for filename in os.listdir(directory):

if filename.lower().endswith(('.png', '.jpg', '.jpeg')):

total_images += 1

image_path = os.path.join(directory, filename)

print(f"Checking image: {filename}")

if is_blurry(image_path):

print(f"Deleting blurry image: {filename}")

os.remove(image_path)

deleted_blurry += 1

continue

if not has_face(image_path):

print(f"Deleting image without face: {filename}")

os.remove(image_path)

deleted_no_face += 1

print(f"Total images processed: {total_images}")

print(f"Total blurry images deleted: {deleted_blurry}")

print(f"Total images without face deleted: {deleted_no_face}")

# Example usage

directory = 'F:\\aivideo'

process_images(directory)

可以通过调整 is_blurry 函数中的阈值来控制检测图片是否模糊的敏感度。阈值越低,检测到的模糊图片越少;阈值越高,检测到的模糊图片越多。在上面的脚本中,is_blurry 函数默认使用的阈值是 100。个人测试,如果是手机拍摄的照片,阈值设置为20,会比较好;

def is_blurry(image_path, threshold=20):

0 阅读:1

部落人有文化

简介:感谢大家的关注