如下:
path = '输入文件所在的文件夹路径'
import os
import numpy as np
import tifffile as tiff
def read_raw_data(path, dimensions, dtype):
"""
读取 .raw 文件并返回图像数据
:param path: .raw 文件路径
:param dimensions: 图像的行数和列数 (height, width)
:param dtype: 数据类型 (如 'uint16')
:return: 图像数据的 numpy 数组
"""
with open(path, 'rb') as f:
img = np.fromfile(f, dtype=dtype)
img = img.reshape(dimensions)
return img
# 在这里修改存放 raw 文件的文件夹路径
pro_path = '/Users/bcy/Desktop/论文研究2/研究论文/raw转换成tif代码/'
info_dimension = (1536, 1536) # 数据维度 (height, width)
dtype = 'uint16'
# 输出文件夹路径
output_folder = '输出数据所在文件夹的路径'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
print('--批量转换开始--')
for i in range(60, 601, 60):
# 构建 .raw 文件路径
raw_filename = f'I1-{i}.raw'
raw_path = os.path.join(pro_path, raw_filename)
# 检查文件是否存在
if os.path.exists(raw_path):
# 读取 .raw 文件
img_raw = read_raw_data(raw_path, info_dimension, dtype)
# 转置图像
img_raw = img_raw.T
# 构建 .tif 文件路径
tif_filename = f'{i}.tif'
tif_path = os.path.join(output_folder, tif_filename)
# 保存为 .tif 文件
tiff.imwrite(tif_path, img_raw, photometric='minisblack', dtype=img_raw.dtype)
print(f'{raw_filename} 转换完成')
else:
print(f'{raw_path} 文件不存在')
print('--批量转换结束--')
有的朋友反馈上面的代码转换出来的TIFF文件的位深度是32,有没有办法可以设置位深度,将生成 位深度为16 的 TIFF文件?
下面的代码可以尝试一下:
import os
from PIL import Image
import numpy as np
def read_raw_data(file_path, dimensions, dtype):
raw_data = np.fromfile(file_path, dtype=dtype)
print(f"Reading raw data from: {file_path}")
print(f"Expected dimensions: {dimensions}")
expected_length = dimensions[0] * dimensions[1]
if len(raw_data) != expected_length:
raise ValueError(f"Data length {len(raw_data)} does not match expected shape {expected_length}")
img = raw_data.reshape(dimensions)
return img
def save_tif_32bit(img_data, output_file):
tif_data = img_data.astype(np.float32)
tif_image = Image.fromarray(tif_data, mode='F')
tif_image.save(output_file, format='TIFF')
# Configuration
pro_path = 'G:\\水果投影数据0701\\好果投影图\\0518_L3_K\\'
info_dimension = (1536, 1536)
dtype = np.uint16
output_folder = 'G:\\水果投影数据0701\\好果投影图\\0518_L3_K-tif\\'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Batch process files
for i in range(60, 601, 60):
input_file = os.path.join(pro_path, f'I1-{i}.raw')
output_file = os.path.join(output_folder, f'{i}.tif')
try:
img_raw = read_raw_data(input_file, info_dimension, dtype)
img_raw = img_raw.T # Transpose the image data if necessary
save_tif_32bit(img_raw, output_file)
print(f"Saved: {output_file}")
except Exception as e:
print(f"Failed to process {input_file}: {e}")
修改了tiff.imwrite函数的传入参数:
# 保存为 .tif 文件,确保位深度为16
tiff.imwrite(tif_path, img_raw.astype(np.uint16), photometric='minisblack')