Python 图片批量处理(图片批量rename,图片批量resize,图片批量split,图片批量concat)

 rename.py(重命名)

import os
class BatchRename():
    '''
    批量重命名文件夹中的图片文件
    '''

    def __init__(self):
        self.path = 'xxxxxxxx'  # 表示需要命名处理的文件夹

    def rename(self):
        filelist = os.listdir(self.path)  # 获取文件路径
        total_num = len(filelist)  # 获取文件长度(个数)
        i = 1  # 表示文件的命名是从1开始的
        for item in filelist:
            if item.endswith('.png'):  # 初始的图片的格式为jpg格式的
                src = os.path.join(os.path.abspath(self.path), item)
                dst = os.path.join(os.path.abspath(self.path), '' + str(i) + '.png')
                try:
                    os.rename(src, dst)
                    print('将 %s 重命名为: %s ...' % (src, dst))
                    i = i + 1
                except:
                    continue
        print('总共重命名 %d 个文件' % total_num)


if __name__ == '__main__':
    demo = BatchRename()
    demo.rename()

resize.py

import os
from PIL import Image

original_images_path = r'初始的图片路径'
combined_images_path = r'图片的保存路径'

#重置图片大小
resize_height = 512
resize_weidth = 512

def find_images(path):
    result = []
    for filename in os.listdir(path):
        _, ext = os.path.splitext(filename.lower())
        if ext == ".jpg" or ext == ".png":
            result.append(os.path.join(path, filename))
            pass
        pass
    result.sort()
    return result

if __name__ == '__main__':
    original_images = find_images(original_images_path)
    for image_path in original_images:
        img_name = image_path[len(original_images_path):]
        original = Image.open(image_path)
        img_color = original.resize((resize_weidth, resize_height), Image.ANTIALIAS)
        img_color.save(combined_images_path + img_name, quality=95)
        print(img_name)
        pass

 split.py (图片分割)

import cv2
import os
if __name__ == "__main__":
    path = "xxxxxxx"  # 将此目录下的图片一分为二(左右分割,即width/2)
    listdir = os.listdir(path)

    for i in listdir:
        if i.split('.')[1] == "png":  # the format of zed img.
            filepath = os.path.join(path, i)
            filename = i.split('.')[0]
            leftpath = os.path.join('xxx', filename) + ".png"#左图目录
            rightpath = os.path.join('xxx', filename) + ".png"#右图目录

            img = cv2.imread(filepath)
            [h, w] = img.shape[:2]
            print(filepath, (h, w))
            limg = img[:, :int(w / 2), :]
            rimg = img[:, int(w / 2 ):, :]

            cv2.imwrite(leftpath, limg)
            cv2.imwrite(rightpath, rimg)

concat.py(图片合并,需要确保两个文件夹目录下的图片的文件名一致)

import cv2 as cv
import numpy as np
import requests
import os
import math
import fnmatch
import shutil
import time
import datetime
import json
import re

def is_file_match(filename, patterns):
    """
    判断文件是否符合判定条件 patterns
    :param filename: 目标检测文件名
    :param patterns: 文件对比条件
    :return: 返回判断结果 匹配成功返回True 匹配失败返回False
    """
    for pattern in patterns:
        if fnmatch.fnmatch(filename, pattern):
            return True
    return False

def find_special_files(root, patterns=['*'], exclude_dirs=[], exclude_files=['.DS_Store']):
    """
    寻找特定文文件夹中各个符合筛选条件文件的路径
    :param root: 文件路径
    :param patterns: 文件类别
    :param exclude_dirs: 排除特定文件夹
    :param exclude_files: 排除特定文件
    :return: 返回文件夹中各个符合筛选条件文件的路径(迭代器)
    """
    for root, dirnames, filenames in os.walk(root):
        for filename in filenames:
            if filename not in exclude_files:
                if is_file_match(filename, patterns):
                    yield os.path.join(root, filename)
        for d in exclude_dirs:
            if d in dirnames:
                dirnames.remove(d)


for i in find_special_files(root=r'图片路径,因为需要合并的两个文件夹目录下的文件的文件名一致,所以此路径可以是两个文件夹中的任意一个', patterns=['*.png']):
    # 可以修改, os.path.basename(i) 是输入的地址
    name = os.path.basename(i)
#合并路径1、2目录下文件名相同的图片
    img1_p = os.path.join(r'路径1', name)
    img2_p = os.path.join(r'路径2', name)
    img1 = cv.imread(img1_p)
    img2 = cv.imread(img2_p)
    img = np.hstack((img1, img2))
    # for j in range(1,14001):
    path = os.path.join('保存路径', name) + ".png"
    cv.imwrite(path, img)


你可能感兴趣的:(python,图像处理,开发语言)