import os
import cv2
import numpy as np
from osgeo import gdal
from skimage import io
source_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_file
image_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] = gray
image[:, :, 1] = gray
image[:, :, 2] = gray
#tiff转jpg
image = 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 io
source_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_file
image_name = target_dir + "\\" + name + ".jpg"
img = cv2.imread(os.path.join(source_dir, image_file))
cv2.imwrite(image_name, img) # 图片存储
print("finish" + " " + image_name)