有时间打算把写的一些小工具代码整理一下。这是第一篇。
Introduction
本文讲图片批量缩放。
缩放方式有很多,本文仅采用按长边等于约定尺寸,短边等比例缩放。对于高>宽的图像,一律进行旋转,使其高边为短边。
对于输入的文件夹,可以包含子文件夹,代码将逐一遍历各个文件夹下所有图片进行处理,并保存在同一个目录里。(也可以分别保存,这部分代码可以自行修改)。如果保存路径不存在,则自动创建目录。
代码采用python,opencv
Code
resize_img.py
# Filename: resize_img.py
# Update: 2020-7
# Autor: Jiejing.Ma
import cv2
import os
import argparse
import numpy as np
‘’‘
Parse commands arguments
’‘’
def parse_args():
parser = argparse.ArgumentParser(description='Resize pictures.', add_help=True, allow_abbrev=True)
parser.add_argument('-i', '--input',
help='picture directories input path. Can include sub dir and soft links.',
# type=str,
required=True)
parser.add_argument("-s", '--save',
help='save resized pictures file path',
# type=str,
required=True)
parser.add_argument('--width',
help='resize width. default=512',
type=int,
required=False,
default=512)
args = parser.parse_args()
return args
def main():
args = parse_args()
source_path = args.input
save_path = args.save
if args.width is not None:
width = args.width
else:
width = 512
# create save_path
if not os.path.exists(save_path):
os.makedirs(save_path)
# iterator folders
ff = os.walk(source_path, followlinks=True)
ext = ['.png', '.jpg', '.jpeg', '.PNG', '.JPG', '.JPEG']
for root, dirs, files in ff:
for file in files:
if file.endswith(tuple(ext)):
dst_file = save_path + file
# 解决文件处理一半后重启程序,不必重新保存问题。
if (os.path.exists(dst_file)):
continue
# 正常处理与保存
else:
src_file = os.path.join(root, file)
img1 = cv2.imread(src_file)
print("source shape {}".format(img1.shape))
# if h>w ,rotate
if img1.shape[0] > img1.shape[1]:
img1 = np.rot90(img1)
print("rotated shape {}".format(img1.shape))
# resize as 512*_(keep ratio)
fx = width / img1.shape[1]
fy = fx
img2 = cv2.resize(img1, (0, 0), fx=fx, fy=fy, interpolation=cv2.INTER_AREA)
print("resize shape {}".format(img2.shape))
print("save as {}".format(dst_file))
cv2.imwrite(dst_file, img2)
return
if __name__ == "__main__":
main()
Usage
$ python ./resize_img.py -i input -s save -w 512
【都看到这儿了,点个赞再走呗^ - ^】