批量打标签、图片批量重命名、批量修改图片尺寸

这篇文章提供了三个Python脚本,分别用于批量修改图片尺寸、批量重命名图片以及批量为图片打标签。脚本利用了PIL库处理图像尺寸,os模块进行文件操作,如重命名和文件路径管理。批量处理适用于大量图片的数据预处理工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1.批量修改图片尺寸

2.图片批量重命名

3.批量打标签


1.批量修改图片尺寸

# coding=utf-8
from PIL import Image
import os

# 此处设置自己要修改成的尺寸
image_width = 800
image_height = 745


def fixed_size(filePath, savePath):
    """按照固定尺寸处理图片"""
    im = Image.open(filePath)
    out = im.resize((image_width, image_height), Image.ANTIALIAS)
    out.save(savePath)


def changeSize():
    #  原图片所在位置
    filePath = r'E:\Users\xxx\Desktop\HOG_SVM-master\data\val\bad'
    #  修改后图片的所在位置
    destPath = r'E:\Users\liukang\Desktop\HOG_SVM-master\data\val\bad-1'
    # os.path模块主要用于文件的属性获取,exists是“存在”的意思,所以顾名思义
    # os.path.exists()就是判断括号里的文件是否存在的意思,括号内的可以是文件路径。存在返回 True 不存在返回 False
    if not os.path.exists(destPath):
        # makedirs 用于递归创建多层目录
        os.makedirs(destPath)
        # 取得该文件夹下的所有文件
    for root, dirs, files in os.walk(filePath):
        for file in files:
            if file[-1] == 'g':
                fixed_size(os.path.join(filePath, file), os.path.join(destPath, file))
    print('Done')


if __name__ == '__main__':
    changeSize()

2.图片批量重命名

# 批量重命名
file_path = "E:/Users/xxx/Desktop/data/bad/"  # 原文件路径
new_path = "E:/python/data/bad/"  # 新文件路径

def rename(path):
    i = 0
    filelist = os.listdir(path)
    for files in filelist[:500]:   # 取文件夹中前500个文件
        oldDirpath = os.path.join(path, files)
        # if os.path.isdir(oldDirpath):  # 如果文件夹中还有文件夹,则进行递归操作
        #     rename(oldDirpath)
        filename = os.path.splitext(files)[0]
        filetype = os.path.splitext(files)[1]
        newDirPath = os.path.join(new_path, 'B'+str(i)+filetype)
        # print(filename, filetype)
        os.rename(oldDirpath, newDirPath)
        i += 1
    print("共有文件数目:", i)

rename(file_path)

原代码

file_path = "/Users/***/Tooth-Detection/data/"  # 原文件路径
new_path = "/Users/***/Tooth-Detection/data/"   # 新文件路径
def rename(path):
    i = 0
    filelist = os.listdir(path)
    for files in filelist[:500]:   # 取文件夹中前500个文件
        oldDirpath = os.path.join(path, files)
        # if os.path.isdir(oldDirpath):  # 如果文件夹中还有文件夹,则进行递归操作
        #     rename(oldDirpath)
        filename = os.path.splitext(files)[0]
        filetype = os.path.splitext(files)[1]
        newDirPath = os.path.join(new_path+'/teeth', 'Y'+str(i)+filetype)
        # print(filename, filetype)
        os.rename(oldDirpath, newDirPath)
        i += 1
    print("共有文件数目:", i)

rename(file_path)

如果原始数据的后缀不一样,还需要重新修改后缀。我又只改了名字,没改后缀,所以现在我写个脚本修改后缀名:

file_path = "/Users/***/Tooth-Detection/data/teeth/"
filelist = os.listdir(file_path)
for files in filelist:
    portion = os.path.splitext(files)
    if portion[1] == '.JPG':
        newname = portion[0] + '.jpg'
        print(newname)
        os.rename(files, newname)

        # 要是报错 使用下面这句

        # os.rename(os.path.join(file_path, files), os.path.join(file_path, newname))

print("finished!")

3.批量打标签

import os


def generate(dir, label):
    files = os.listdir(dir + r'/good')  # os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表
    with open(dir + 'val.txt', 'a+') as f:  # a:	打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。'val.txt'可以改为'.txt'
        # 文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写
        for file in files:  # 遍历的文件夹中的 文件 集合
            filename = os.path.split(file)[0]  # 按照路径将文件名和路径分割开
            filetype = os.path.split(file)[1]
            print(filename, filetype)
            if filetype == '.txt':
                continue
            name = '/good' + '/' + file + ' ' + str(int(label)) + '\n'
            f.write(name)
    print("finished!")


img_path = r'E:\Users\xxx\Desktop\HOG_SVM-master\data\val'

if __name__ == '__main__':
    i = 1
    generate(img_path, i)

原代码

import os

def generate(dir, label):
    files = os.listdir(dir+'/teeth')
    with open(dir+'val.txt', 'a+') as f:
        for file in files:
            filename = os.path.split(file)[0]
            filetype = os.path.split(file)[1]
            print(filename, filetype)
            if filetype == '.txt':
                continue
            name = '/teeth' + '/' + file + ' ' + str(int(label)) + '\n'
            f.write(name)
    print("finished!")

img_path = '/Users/***/Tooth-Detection/data/val/'

if __name__ == '__main__':
    i = 1
    generate(img_path, i)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值