import argparse import logging import re from multiprocessing import Process, Queue from pathlib import Path import numpy as np from skimage import exposure, filters from modules.config import logger from modules.volume import volume_loading_func, volume_saving_func def normalize_intensity( np_volume: np.ndarray, relative_path: Path, logger: logging.Logger ): logger.info(f"[processing start] {relative_path}") nstack = len(np_volume) stack: np.ndarray = np_volume[nstack // 2 - 16 : nstack // 2 + 16] hist_y, hist_x = exposure.histogram(stack[stack > 0]) thr = filters.threshold_otsu(stack[stack > 0]) peak_air = np.argmax(hist_y[hist_x < thr]) + hist_x[0] peak_soil = np.argmax(hist_y[hist_x > thr]) + (thr - hist_x[0]) + hist_x[0] np_volume = np_volume.astype(np.int64) for i in range(len(np_volume)): np_volume[i] = ( (np_volume[i] - peak_air).clip(0) / (peak_soil - peak_air) * 256 / 2 ) logger.info(f"[processing end] {relative_path}") return exposure.rescale_intensity( np_volume, in_range=(0, 255), out_range=(0, 255) ).astype(np.uint8) 请详细解释每一行的代码意思
时间: 2023-06-02 19:04:48 浏览: 169
这段代码是对给定的三维图像进行强度归一化的函数,下面是每行代码的解释:
```
import argparse # 导入命令行参数解析模块
import logging # 导入日志模块
import re # 导入正则表达式模块
from multiprocessing import Process, Queue # 导入多进程相关模块
from pathlib import Path # 导入文件路径相关模块
import numpy as np # 导入数组操作模块
from skimage import exposure, filters # 导入图像处理模块
from modules.config import logger # 导入配置和日志模块
from modules.volume import volume_loading_func, volume_saving_func # 导入3D图像加载和保存模块
# 定义一个函数,输入包含三维图像数据的数组、图像相对路径和日志对象,输出经过归一化的图像数组
def normalize_intensity(np_volume: np.ndarray, relative_path: Path, logger: logging.Logger):
logger.info(f"[processing start] {relative_path}")
# 首先对数组进行切片,nstack是数组的第一维度大小,即切片后数组的深度
nstack = len(np_volume)
stack: np.ndarray = np_volume[nstack // 2 - 16 : nstack // 2 + 16]
# 对切片后的数组进行直方图均衡化,并求出阈值thr和两个峰值peak_air和peak_soil
hist_y, hist_x = exposure.histogram(stack[stack > 0])
thr = filters.threshold_otsu(stack[stack > 0])
peak_air = np.argmax(hist_y[hist_x < thr]) + hist_x[0]
peak_soil = np.argmax(hist_y[hist_x > thr]) + thr - hist_x[0]
# 将数组转换成int64数据类型并进行归一化
np_volume = np_volume.astype(np.int64)
for i in range(len(np_volume)):
np_volume[i] = (
(np_volume[i] - peak_air).clip(0) /
(peak_soil - peak_air) * 256 / 2
)
logger.info(f"[processing end] {relative_path}")
# 对归一化后的图像进行范围调整并返回
return exposure.rescale_intensity(
np_volume, in_range=(0, 255), out_range=(0, 255)
).astype(np.uint8)
```
该函数首先对图像进行切片,取中间32层进行处理。在这些层中,使用直方图均衡化算法获取阈值和两个峰值,并将其用于将输入的三维数组进行归一化处理。最后将处理后的图像进行范围调整,使其在0-255范围内,并将数组的类型转换为uint8,然后返回处理后的图像数组。
阅读全文