您的位置:首页 > 编程语言 > Python开发

Python下OpenCV批量调整图片大小——整理分团委资料的小技巧

2018-03-20 00:46 916 查看
上个周末一直在整理申请红旗分团委的资料,本想着今天终于可以干干其他事情了,结果整理的资料“啪”一下被打回来,原来是没有插入奖状的证明照片。插入奖状的照片是个麻烦事,因为照片是每个人自己照的,每个人拍出来的照片尺寸大小不一,如果一张一张调整后插入将会形成海量的工作量。这个时候突然想到OpenCV可以用来批量调整图像,于是就动手试了试,用python写了个脚本。这个脚本在网上找了半个轮子,自己造了半个轮子,分享在这里。

# -*- coding: utf-8 -*-

from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import sys
import os
# import threading
import cv2

# from PIL import Image
print(("shell name:"), sys.argv[0])
print('params list:', str(sys.argv))

if (len(sys.argv) != 5):
print(
'the input params should be equal to 4, namely the content, the picture format(eg jpg),the susbsize image height, the subsize image width')
sys.exit(1)

for i in range(1, len(sys.argv)):
print("param", i, sys.argv[i])

rootContent = sys.argv[1];
suffixFile = sys.argv[2];
heightsubImage = int(sys.argv[3]);
widthsubImage = int(sys.argv[4]);

def resize(dirFile, suffix):
for file in os.listdir(dirFile):
singlefileName = dirFile + "/" + file
singlefileForm = os.path.splitext(singlefileName)[1][1:]
if (singlefileForm == suffix):
print('loading................ : ', singlefileName)
oriImage = cv2.imread(singlefileName)
print(singlefileName)
oriHei = oriImage.shape[0]
oriWid = oriImage.shape[1]
if (oriHei <= heightsubImage | oriWid <= widthsubImage):
print('image :', singlefileName, 'is smaller than the specified shape')
sys.exit(1)

# creat a new subcontent to store the subimages and place it to the upper content
newSubContent = os.path.splitext('/Users/Hosea/Desktop')[0][0:]
if (os.path.exists(newSubContent) == False):
os.mkdir(newSubContent)

subImages = cv2.resize(oriImage, (widthsubImage, heightsubImage))

# wirte the image to the new created subcontent
savefile = newSubContent + "/" + 'Output' + "/" + os.path.splitext(file)[0][0:]  + '.' + suffix
cv2.imwrite(savefile, subImages)
print('finish writting')

resize(rootContent, suffixFile)


在python运行语句后面一次加上文件夹路径、文件类型、设定高度、设定宽度,用空格隔开,回车运行脚本。



运行结束后,插入图片,就都是一个尺寸的啦。



参考资料:https://download.csdn.net/download/amrser/9951243
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息