

我的檔案分布如上,本方法可實作一鍵修改所有圖片檔案的格式,例如將現有的png格式修改為jpg格式,
下面上代碼:
import os
from PIL import Image
# 圖片路徑
CONVERT_PATH = "D:\\dataset\\test"
files = os.listdir(CONVERT_PATH) #找到所有檔案串列
# 轉換串列
List= []
print(files)
# n,e=os.path.splitext("E:\\dataset\\train\\001\\1image1.jpg")
# print(n,e)
# a=os.path.join('"E:\\dataset\\train\\001',n)
# print(a)
# 遍歷檔案夾,儲存webp格式的路徑到串列內
def convertImage(filePath):
a_files = os.listdir(filePath) #把filepath下的檔案全部列出來包括檔案夾,但只有一級
for a_files_name in a_files:
sPath = os.path.join(filePath,a_files_name)
if os.path.isdir(sPath): #存在例如001的檔案夾
convertImage(sPath) #如果是檔案夾就繼續遞回檢索
c,d = os.path.splitext(sPath)
if d == ".png":
List.append(c)
for file_name in files: #file_name為001,002,003等
nPath = os.path.join(CONVERT_PATH, file_name)
# 檔案夾
if os.path.isdir(nPath): #判斷是不是目錄
convertImage(nPath)
elif os.path.isfile(nPath): #這里是用來判斷路徑下是不是直接存在圖片,例如0001.jpg
a,b=os.path.splitext(nPath)
if b==".png":
List.append(a)
def convert():
for jpgPath in List:
img = Image.open(jpgPath+".png") #打開png格式的圖片
img.save(jpgPath+".jpg") #修改格式為jpg
os.remove(jpgPath+".png") #洗掉原來的png格式圖片
convert()
基本都在注釋里注明了代碼的功能了,不過有個地方需要說一下,c,d = os.path.splitext(sPath),這里splitext的作用是傳入sPath路徑后,將檔案的后綴與前面分隔開,例如sPath="D:\dataset\test\001\000001.png",這時c等于D:\dataset\test\001\000001,而d等于.png
其他地方應該比較好理解了,下面就是結果了

當然可以修改為任何的格式,只需將代碼中的.jpg改成你想要的格式即可,
img.save(jpgPath+".jpg") #修改格式為jpg
文章到這就結束啦

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/401507.html
標籤:其他
