1. 程式人生 > >Python下OpenCV批量調整圖片大小——整理分團委資料的小技巧

Python下OpenCV批量調整圖片大小——整理分團委資料的小技巧

上個週末一直在整理申請紅旗分團委的資料,本想著今天終於可以乾乾其他事情了,結果整理的資料“啪”一下被打回來,原來是沒有插入獎狀的證明照片。插入獎狀的照片是個麻煩事,因為照片是每個人自己照的,每個人拍出來的照片尺寸大小不一,如果一張一張調整後插入將會形成海量的工作量。這個時候突然想到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執行語句後面一次加上資料夾路徑、檔案型別、設定高度、設定寬度,用空格隔開,回車執行指令碼。
執行結果

執行結束後,插入圖片,就都是一個尺寸的啦。
插入圖片