python 文件夾中的文件批量處理 高通道tif圖片轉換成jpg格式

在數據集的製作中,往往涉及到 文件夾中文件的批量處理操作,而首要的任務便是將獲得的數據進行重命名以方便批量讀取,隨後再進行操作。

一、文件批量重命名

文件夾的批量處理操作關鍵在於用os庫的os.listdir()獲得目錄下所有文件的列表,隨後就可以進行遍歷操作。
代碼如下:

import os,sys
def rename(path):        #定義函數名稱
    filelist=os.listdir(path)#獲取當前路徑下的文件列表
    i=0#w文件的編碼序號
    for oldname in filelist:#遍歷列表下的文件名,其中oldname與files列表自動對應
        newname="2018_"+str(i)+".tif"#文件的前綴、標號和後綴的字符串拼接
        os.rename(os.path.join(path,oldname),os.path.join(path,newname))
        #rename()將源文件的名字進行替換  os.path.join()進行兩個字符串的拼接
        print(newname)#輸出文件的名字
        i=i+1#編碼加一

二、高通道TIF圖片格式轉換

高通道的TIF圖片有四個通道的信息,要想能夠看到必須進行格式轉化,將16位圖片4通道轉換成兩個8位圖片,分別是三通道的彩色圖片和單通道的近紅外灰度圖片。
代碼如下:

import os,sys
import cv2
import numpy
from skimage import io#使用IO庫讀取tif圖片
#文件遍歷+上面定義的轉換函數
def tif_jpg_transform(file_path_name,bgr_savepath_name,nir_savepath_name):
    img = io.imread(file_path_name)#讀取文件名
    img = img / img.max()#使其所有值不大於一
    img = img * 255 - 0.001  # 減去0.001防止變成負整型
    img = img.astype(np.uint8)#強制轉換成8位整型
    print(img.shape)  # 顯示圖片大小和深度
    b = img[:, :, 0]  # 讀取藍通道
    g = img[:, :, 1]  # 讀取綠通道
    r = img[:, :, 2]  # 讀取紅通道
    nir = img[:, :, 3]  # 近紅外通道
    print(nir.shape)#顯示近紅外圖片shape
    bgr = cv2.merge([b, g, r])  # 通道拼接
    cv2.imwrite(bgr_savepath_name, bgr)#圖片存儲
    cv2.imwrite(nir_savepath_name, nir)
    #驗證代碼
    #cv2.imshow('bgr', bgr)
    #cv2.imshow("nir",nir)
    #cv2.waitKey(0)
    #cv2.destroyAllWindows()
    
##########################以下爲驗證代碼
file_path=r'F:\BaiduNetdiskDownload\test\img_2017'#前面r''表示不用轉義
bgr_savepath=r'F:\BaiduNetdiskDownload\test\bgr_2017'
nir_savepath=r'F:\BaiduNetdiskDownload\test\nir_2017'

file_path_name=file_path+'/'+'2017_0.tif'#字符串拼接注意加斜槓
bgr_savepath_name=bgr_savepath+'/'+'2017_0.jpg'
nir_savepath_name=nir_savepath+'/'+'2017_0.jpg'

三、圖片格式的批量轉換

def batch_processing(file_path,bgr_savepath,nir_savepath):
    filelist=os.listdir(file_path)#獲取當前路徑下的文件列表
    i=0#文件的編碼序號
    for name in filelist:#遍歷列表下的文件名,其中name與filelist自動對應
    
        file_path_name = file_path+"/"+name#源文件路徑
        bgr_savepath_name = bgr_savepath + '/' + '2018_'+str(i)+'.jpg'#BGR圖像存儲路徑
        nir_savepath_name = nir_savepath + '/' + '2018_'+str(i)+'.jpg'#NIR圖像存儲路徑
        
        print(file_path_name)#輸出文件名進行反饋操作
        tif_jpg_transform(file_path_name, bgr_savepath_name, nir_savepath_name)#圖像轉換
        i+=1#編碼+1
##########設定路徑
file_path=r'F:\BaiduNetdiskDownload\test\img_2018'
bgr_savepath=r'F:\BaiduNetdiskDownload\test\bgr_2018'
nir_savepath=r'F:\BaiduNetdiskDownload\test\nir_2018'
batch_processing(file_path,bgr_savepath,nir_savepath)
發佈了3 篇原創文章 · 獲贊 1 · 訪問量 231
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章