python 单通道tiff图转jpg
生活随笔
收集整理的這篇文章主要介紹了
python 单通道tiff图转jpg
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import os
import cv2
import numpy as np
from osgeo import gdal
from skimage import iosource_dir = 'D:\desk\dm\Acky\BaseNet\data_set\FUSARship-t-v\\val\\tug' # 源tiff圖路徑
target_dir = 'D:\desk\dm\Acky\BaseNet\data_set\FUSARship-1\\val\\tug' # 保存到的jgp路徑# 如果目標目錄不存在的話,進行目錄的新建
if not os.path.exists(target_dir):os.makedirs(target_dir)
files = os.listdir(source_dir)for image_file in files:name = []portion = os.path.splitext(image_file) # 把文件名拆分為名字和后綴if portion[1] == ".tiff":name = portion[0]image_path = source_dir + "\\" + image_fileimage_name = target_dir + "\\" + name + ".jpg"#讀取tiff圖片(我的全是單通道,如果需要可以寫if判斷一下是單還是三通道)img = cv2.imread(os.path.join(source_dir, image_file))gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)image = np.zeros_like(img)image[:, :, 0] = grayimage[:, :, 1] = grayimage[:, :, 2] = gray#tiff轉jpgimage = image / image.max() # 使其所有值不大于一image = image * 255 - 0.001 # 減去0.001防止變成負整型image = image.astype(np.uint8) # 強制轉換成8位整型b = image[:, :, 0] # 讀取藍通道g = image[:, :, 1] # 讀取綠通道r = image[:, :, 2] # 讀取紅通道bgr = cv2.merge([r, g, b]) # 通道拼接cv2.imwrite(image_name, bgr) # 圖片存儲print("finish" + " " + image_name)
后續修改+補充:cv2.imread讀取默認轉為三通道rgb圖像
所以從思路來看可以直接cv2.imread讀取為rgb圖,并拆分img的名字和后綴,將后綴改為jpg即可了,簡單方便。
image_B = cv2.imread((self.files_B[random.randint(0, len(self.files_B) - 1)]), 0)# 第二個參數是通道數和位深的參數,# IMREAD_UNCHANGED = -1 # 不進行轉化,比如保存為了16位的圖片,讀取出來仍然為16位。# IMREAD_GRAYSCALE = 0 # 進行轉化為灰度圖,比如保存為了16位的圖片,讀取出來為8位,類型為CV_8UC1。# IMREAD_COLOR = 1 # 進行轉化為RGB三通道圖像,圖像深度轉為8位# IMREAD_ANYDEPTH = 2 # 保持圖像深度不變,進行轉化為灰度圖。# IMREAD_ANYCOLOR = 4 # 若圖像通道數小于等于3,則保持原通道數不變;若通道數大于3則只取取前三個通道。圖像深度轉為8位 import os import cv2 import numpy as np from osgeo import gdal from skimage import iosource_dir = 'D:\desk\dm\Acky\BaseNet\data_set\FUSARship-t-v\\val\\tug' # 源tiff圖路徑 target_dir = 'D:\desk\dm\Acky\BaseNet\data_set\FUSARship-1\\val\\tug' # 保存到的jgp路徑# 如果目標目錄不存在的話,進行目錄的新建 if not os.path.exists(target_dir):os.makedirs(target_dir) files = os.listdir(source_dir)for image_file in files:name = []portion = os.path.splitext(image_file) # 把文件名拆分為名字和后綴if portion[1] == ".tiff":name = portion[0]image_path = source_dir + "\\" + image_fileimage_name = target_dir + "\\" + name + ".jpg"img = cv2.imread(os.path.join(source_dir, image_file))cv2.imwrite(image_name, img) # 圖片存儲print("finish" + " " + image_name)總結
以上是生活随笔為你收集整理的python 单通道tiff图转jpg的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 北大计算机博士有多难考,我是怎样考上北大
- 下一篇: Python Pillow批量转换tif