700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python 文件夹中的文件批量处理 高通道tif图片转换成jpg格式

python 文件夹中的文件批量处理 高通道tif图片转换成jpg格式

时间:2020-09-29 12:10:43

相关推荐

python 文件夹中的文件批量处理 高通道tif图片转换成jpg格式

在数据集的制作中,往往涉及到 文件夹中文件的批量处理操作,而首要的任务便是将获得的数据进行重命名以方便批量读取,随后再进行操作。

一、文件批量重命名

文件夹的批量处理操作关键在于用os库的os.listdir()获得目录下所有文件的列表,随后就可以进行遍历操作。

代码如下:

import os,sysdef rename(path): #定义函数名称filelist=os.listdir(path)#获取当前路径下的文件列表i=0#w文件的编码序号for oldname in filelist:#遍历列表下的文件名,其中oldname与files列表自动对应newname="_"+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,sysimport cv2import numpyfrom 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)#显示近红外图片shapebgr = 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_'#前面r''表示不用转义bgr_savepath=r'F:\BaiduNetdiskDownload\test\bgr_'nir_savepath=r'F:\BaiduNetdiskDownload\test\nir_'file_path_name=file_path+'/'+'_0.tif'#字符串拼接注意加斜杠bgr_savepath_name=bgr_savepath+'/'+'_0.jpg'nir_savepath_name=nir_savepath+'/'+'_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 + '/' + '_'+str(i)+'.jpg'#BGR图像存储路径nir_savepath_name = nir_savepath + '/' + '_'+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_'bgr_savepath=r'F:\BaiduNetdiskDownload\test\bgr_'nir_savepath=r'F:\BaiduNetdiskDownload\test\nir_'batch_processing(file_path,bgr_savepath,nir_savepath)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。