Python實現(xiàn)批量修改圖片格式和大小的方法【opencv庫與PIL庫】
本文實例講述了Python實現(xiàn)批量修改圖片格式和大小的方法。分享給大家供大家參考,具體如下:
第一種方法用到opencv庫
import os import time import cv2 def alter(path,object): result = [] s = os.listdir(path) count = 1 for i in s: document = os.path.join(path,i) img = cv2.imread(document) img = cv2.resize(img, (20,20)) listStr = [str(int(time.time())), str(count)] fileName = ''.join(listStr) cv2.imwrite(object+os.sep+'%s.jpg' % fileName, img) count = count + 1 alter('C:\\imgDemo','C:\\imgDemo1')
第二種方法用到PIL庫
import os import time from PIL import Image def alter(path,object): s = os.listdir(path) count = 1 for i in s: document = os.path.join(path,i) img = Image.open(document) out = img.resize((20,20)) listStr = [str(int(time.time())), str(count)] fileName = ''.join(listStr) out.save(object+os.sep+'%s.jpg' % fileName) count = count + 1 alter('C:\\imgDemo','C:\\imgDemo1')
運(yùn)行上述代碼可得到C:\imgDemo目錄下對應(yīng)批量生成的20*20大小的圖片。
運(yùn)行效果如下:
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
關(guān)于使用python對mongo多線程更新數(shù)據(jù)
這篇文章主要介紹了關(guān)于使用python對mongo多線程更新數(shù)據(jù),文中提供了詳細(xì)的代碼說明,實際使用時,需要根據(jù)具體情況進(jìn)行調(diào)整和優(yōu)化,需要的朋友可以參考下2023-04-04全網(wǎng)最細(xì) Python 格式化輸出用法講解(推薦)
這篇文章主要介紹了全網(wǎng)最細(xì) Python 格式化輸出用法講解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01