Files
micro_plastic/bil2rgb.py
2026-02-25 09:42:51 +08:00

54 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import numpy as np
from spectral.io import envi
from PIL import Image
import matplotlib.pyplot as plt
import os
def linear_stretch_2_percent(data):
"""
应用2%线性拉伸到数据
参数:
data: 输入的单波段数据
返回:
拉伸后的数据 (0-255)
"""
# 计算2%和98%的分位数
low = np.percentile(data, 2)
high = np.percentile(data, 98)
# 应用线性拉伸
stretched = np.clip((data - low) / (high - low), 0, 1) * 255
return stretched.astype(np.uint8)
def process_bil_files(input_folder):
"""
处理BIL文件读取10、60、160波段并导出为PNG
参数:
input_folder: 包含BIL文件的输入文件夹
"""
# 读取BIL文件
img = envi.open(input_folder.replace('.bil', '.hdr'), input_folder)
# 读取指定波段10, 60, 160
# 注意波段索引从0开始所以10波段是索引9以此类推
band_10 = img.read_band(9)
band_60 = img.read_band(59)
band_160 = img.read_band(159)
# 应用2%线性拉伸到每个波段
band_10_stretched = linear_stretch_2_percent(band_10)
band_60_stretched = linear_stretch_2_percent(band_60)
band_160_stretched = linear_stretch_2_percent(band_160)
# 创建RGB图像分别对应10,60,160波段
rgb_img = np.stack([band_10_stretched, band_60_stretched, band_160_stretched], axis=-1)
# 将NumPy数组转换为PIL图像
# 确保值在0-255范围内并转换为uint8类型
rgb_img_pil = Image.fromarray((rgb_img).astype(np.uint8))
return rgb_img_pil