1、提取单张png图像组学特征示例:
import SimpleITK as sitk
import numpy as np
import matplotlib.pyplot as plt
from radiomics import featureextractor
import os
import cv2
def load_image(image_path):
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) # Load image in grayscale
return sitk.GetImageFromArray(image)
if __name__ == '__main__':
# 指定image和mask路径
image_path = 'xxx_img.jpg'
mask_path = 'xxx_mask.png'
# 加载图像
image = load_image(image_path)
mask = load_image(mask_path)
# 获取掩码
mask = sitk.BinaryThreshold(mask, 1, 255, 1, 0)
# 可视化
plt.subplot(1, 2, 1)
plt.imshow(sitk.GetArrayFromImage(image), cmap='gray')
plt.title('Image')
plt.subplot(1, 2, 2)
plt.imshow(sitk.GetArrayFromImage(mask), cmap='gray')
plt.title('Mask')
plt.show()
# 初始化特征提取器
extractor = featureextractor.RadiomicsFeatureExtractor()
# 提取特征
features = extractor.execute(image, mask)
# 打印特征
for feature_name, feature_value in features.items():
print(f'{feature_name}: {feature_value}')
2、遍历文件夹提取多张png图像组学特征示例(数据需要自行准备,一张原图对应一张掩膜图,原图命名格式为*_image.png,掩膜图命名格式为*_label.png,将图像数据放在一个文件夹内即可):
import SimpleITK as sitk
import numpy as np
import matplotlib.pyplot as plt
from radiomics import featureextractor
import os
import cv2
import pandas as pd
def load_image(image_path):
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) # 加载灰度图像
return sitk.GetImageFromArray(image)
# 遍历文件夹内的所有文件
#params = 'Params.yaml'
folder_path = 'data/all'
all_features = []
image_names = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('_image.png'):
image_path = os.path.join(root, file)
mask_path = os.path.join(root, file.replace('_image.png', '_label.png'))
# 加载图像和掩码
image = load_image(image_path)
mask = load_image(mask_path)
# 获取掩码
mask = sitk.BinaryThreshold(mask, 1, 255, 1, 0)
# 初始化特征提取器
extractor = featureextractor.RadiomicsFeatureExtractor()
# 提取特征
extractor.enableAllFeatures()
extractor.enableAllImageTypes()
extractor.enabledFeatures['glcm'] = ['Autocorrelation',
'JointAverage',
'ClusterProminence',
'ClusterShade',
'ClusterTendency',
'Contrast',
'Correlation',
'DifferenceAverage',
'DifferenceEntropy',
'DifferenceVariance',
'JointEnergy',
'JointEntropy',
'Imc1',
'Imc2',
'Idm',
'MCC',
'Idmn',
'Id',
'Idn',
'InverseVariance',
'MaximumProbability',
'SumEntropy',
'SumSquares']
# 由于图像是2D,所以专门去除了GLCM中的3D特征
features = extractor.execute(image, mask)
features_dict = dict(features.items()) # 将特征转换为字典形式
all_features.append(features_dict) # 将字典添加到列表中
image_names.append(file.replace('_image.png', '')) # 记录图像名称
# 将所有特征合并到一个 DataFrame 中
df = pd.DataFrame.from_dict(all_features) # 使用 from_dict 方法并指定 orient='index' 来实现转置
# 添加图像名称作为索引
df['ImageName'] = image_names
df.set_index('ImageName', inplace=True)
# 保存为 Excel 表格
df.to_excel('result.xlsx', index=False, header=True) # 保留表头特征名称和索引
生成的特征数据为:
标签:pyradiomics,plt,组学,image,mask,import,path,png From: https://blog.csdn.net/Gu104/article/details/142150928