由于做数据分析老是要筛选相应图片进行训练,于是写下这段代码,遍历文件夹下所有图片,根据需求筛选想要的图片复制到新文件夹
import os
import shutil
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
'.tif', '.TIF', '.tiff', '.TIFF',
]
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
# file_path = os.sep.join(['D:', 'picture', 'hqyy'])
root_path = r"D:\picture\hqyy"
target = '1'
for root, dirs, files in os.walk(root_path):
'''root 表示当前正在访问的文件夹路径
dirs 表示该文件夹下的子目录名list
files 表示该文件夹下的文件list'''
for file in files:
file_path = os.path.join(root, file)
if is_image_file(file_path):
if file_path.split('\\')[-2] == target:
if not os.path.exists(root_path + os.sep + target):
os.mkdir(root_path + os.sep + target)
shutil.copy2(file_path, os.path.join(root_path + os.sep + target, file))
print(file_path)
import os
import shutil
import re
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
'.tif', '.TIF', '.tiff', '.TIFF',
]
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
# file_path = os.sep.join(['D:', 'picture', 'hqyy'])
root_path = r"D:\picture\终RVO"
target_path = r'D:\picture'
for root, dirs, files in os.walk(root_path):
'''root 表示当前正在访问的文件夹路径
dirs 表示该文件夹下的子目录名list
files 表示该文件夹下的文件list'''
for file in files:
file_path = os.path.join(root, file)
if is_image_file(file_path):
target = re.findall(r'-(\d).', file)
if target:
target = target[0]
if not os.path.exists(target_path + os.sep + target):
os.mkdir(target_path + os.sep + target)
file_name = file_path.split(os.sep)[-3]+'-'+file_path.split(os.sep)[-2]+'.jpeg'
shutil.copy2(file_path, os.path.join(target_path + os.sep + target, file_name))
print(file_path)
本文介绍了一款用于筛选并复制特定图片的Python脚本。该脚本能够遍历指定文件夹下的所有图片,根据预设条件筛选出目标图片,并将它们复制到新的文件夹中。适用于数据集整理等场景。
206





