欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

复制即用-python-读取文件夹中图片并按照最短边裁剪为正方形

程序员文章站 2022-04-09 13:09:04
...

读取文件夹中图片并按照最短边裁剪为正方形

声明

没有技术难度的读取图片并剪裁,偷懒就复制粘贴跑它!

代码

import os
from random import randint
import cv2

def cut_resize_file(source_path, output_path, file_type, cut_size):
    """
    先根据最短边进行裁剪,为正方形,在重设大小,默认256
    :param source_path:
    :param output_path:
    :param file_type:
    :param cut_size:
    :return:
    """
    path_files = os.listdir(source_path)
    for item_name in path_files:
        if item_name.endswith(file_type):  # 扩展名是图片
            # 调用cv2.imread读入图片,读入格式为IMREAD_COLOR
            full_name = source_path + "/" + item_name
            print('process +> ', full_name)
            img_mat = cv2.imread(full_name, cv2.IMREAD_COLOR)
            # 根据最短边进行图像裁剪
            sp = img_mat.shape
            rows = sp[0]  # height(rows) of image
            cols = sp[1]  # width(colums) of image
            if rows >= cols:
                shorter = cols
            else:
                shorter = rows
            cropped = img_mat[0:shorter, 0:shorter]  # 裁剪坐标为[y0:y1, x0:x1]
            new_array = cv2.resize(cropped, cut_size)
            random_name = str(randint(0, 99999)) + '.jpg'  # 随机生成一个数字作为名字
            cv2.imwrite(output_path + '/' + random_name, new_array)


if __name__ == '__main__':
    # 本方法用于将原图依照最短边进行重设大小,并裁剪
    print('执行开始')
    source_path = 'F:/COCO_models/COCO2017/temp/'  # 原图路径
    output_path = './men2autom512/trainA'  # 保存路径
    file_type = '.jpg'  # 文件扩展名
    cut_size = (512, 512)  # 裁剪大小
    cut_resize_file(source_path, output_path, file_type, cut_size)
    print('执行结束')