medical image analysis 笔记1

AI for medical image analysis

1.Data Exploration 课程代码

在本课程的第一个作业中,您将使用从公共 ChestX-ray8 数据拍摄的胸部 X 射线图像。
在本笔记本中,您将有机会探索此数据集并熟悉将在第一次评分作业中使用的一些技巧

在开始为任何机器学习项目编写代码之前,第一步是探索您的数据。用于分析和操作数据的标准 Python 包是 pandas。
使用接下来的两个代码单元格,您将导入 pandas 和一个名为 numpy 的包用于数值操作,然后使用 pandas 将 csv 文件读入数据帧并打印出前几行数据。

# Import necessary packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import os
import seaborn as sns
sns.set()
# Read csv file containing training datadata
train_df = pd.read_csv("nih/train-small.csv")
# Print first 5 rows
print(f'There are {train_df.shape[0]} rows and {train_df.shape[1]} columns in this data frame')
train_df.head()

在这里插入图片描述
查看此 csv 文件中的各个列。该文件包含胸部 X 射线图像的名称(“图像”列),填充有 1 和 0 的列标识基于每个 X 射线图像给出的诊断。

数据类型和空值检查

# Look at the data type of each column and whether null values are present
train_df.info()

在这里插入图片描述

唯一 ID 检查

“PatientId”具有每个患者的标识号。
关于此类医疗数据集,您想了解的一件事是,您是否正在查看某些患者的重复数据,或者每个图像是否代表不同的人。

print(f"The total patient ids are {train_df['PatientId'].count()}, from those the unique ids are {train_df['PatientId'].value_counts().shape[0]} ")

The total patient ids are 1000, from those the unique ids are 928

# pandas value_counts()功能确认数据出现的频率
count = train_df['PatientId'].value_counts()
count.shape
count

(928,)
在这里插入图片描述
如你所见,数据集中唯一患者的数量少于总数,因此必须存在一些重叠。对于有多个记录的患者,您需要确保它们不会同时出现在训练和测试集中,以避免数据泄漏(在本周的讲座中稍后介绍)。

探索数据标签

运行接下来的两个代码单元以创建每个患者状况或疾病的名称列表。

# pandas.keys() 返回pd的列名,而列名里包含不同的疾病
columns = train_df.keys()
columns = list(columns)
print(columns)

在这里插入图片描述

# Remove unnecesary elements
columns.remove('Image')
columns.remove('PatientId')
# Get the total classes
print(f"There are {len(columns)} columns of labels for these conditions: {columns}")

There are 14 columns of labels for these conditions: [‘Atelectasis’, ‘Cardiomegaly’, ‘Consolidation’, ‘Edema’, ‘Effusion’, ‘Emphysema’, ‘Fibrosis’, ‘Hernia’, ‘Infiltration’, ‘Mass’, ‘Nodule’, ‘Pleural_Thickening’, ‘Pneumonia’, ‘Pneumothorax’]

运行下一个单元格以打印出每个条件的正标签 (1) 的数量。

# Print out the number of positive labels for each class
for column in columns:
    print(f"The class {column} has {train_df[column].sum()} samples")

在这里插入图片描述
查看上面每个类中标签的计数。
这看起来像一个平衡的数据集吗?

数据可视化

使用 csv 文件中列出的图像名称,您可以检索与数据框中每一行数据关联的图像。运行下面的单元格以可视化从数据集中随机选择的图像。

# Extract numpy values from Image column in data frame
images = train_df['Image'].values   

# Extract 9 random images from it
random_images = [np.random.choice(images) for i in range(9)]
# #numpy.random.choice(a, size=None, replace=True, p=None)
#从a(只要是ndarray都可以,但必须是一维的)中随机抽取数字,并组成指定大小(size)的数组
#replace:True表示可以取相同数字,False表示不可以取相同数字
#数组p:与数组a相对应,表示取数组a中每个元素的概率,默认为选取每个元素的概率相同。

# Location of the image dir
img_dir = 'nih/images-small/'

print('Display Random Images')

# Adjust the size of your images
plt.figure(figsize=(20,10))

# Iterate and plot random images
for i in range(9):
    plt.subplot(3, 3, i + 1)
    img = plt.imread(os.path.join(img_dir, random_images[i]))
    # 重点 plt还可以直接读取图像,返回numpy.array see https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imread.html
    plt.imshow(img, cmap='gray')
    plt.axis('off')
    
# Adjust subplot parameters to give specified padding
plt.tight_layout()    

在这里插入图片描述

调查单个图像

运行下面的单元格以查看数据集中的第一张图像并打印出图像内容的一些详细信息。

# Get the first image that was listed in the train_df dataframe
sample_img = train_df.Image[0]
raw_image = plt.imread(os.path.join(img_dir, sample_img))
plt.imshow(raw_image, cmap='gray')
plt.colorbar()
plt.title('Raw Chest X Ray Image')
print(f"The dimensions of the image are {raw_image.shape[0]} pixels width and {raw_image.shape[1]} pixels height, one single color channel")
print(f"The maximum pixel value is {raw_image.max():.4f} and the minimum is {raw_image.min():.4f}")
print(f"The mean value of the pixels is {raw_image.mean():.4f} and the standard deviation is {raw_image.std():.4f}")

在这里插入图片描述

  1. List item

调查像素值分布
运行下面的单元格以绘制上图中像素值的分布。
补充一下 seaborn的用法 https://blog.csdn.net/qq_34264472/article/details/53814653

# Plot a histogram of the distribution of the pixels
sns.distplot(raw_image.ravel(), 
             label=f'Pixel Mean {np.mean(raw_image):.4f} & Standard Deviation {np.std(raw_image):.4f}', kde=False)
plt.legend(loc='upper center')
plt.title('Distribution of Pixel Intensities in the Image')
plt.xlabel('Pixel Intensity')
plt.ylabel('# Pixels in Image')

在这里插入图片描述

Keras 中的图像预处理

在训练之前,您将首先修改图像以使其更适合训练卷积神经网络。对于此任务,您将使用 Keras ImageDataGenerator 函数执行数据预处理和数据增强。
运行接下来的两个单元格以导入此函数并创建用于预处理的图像生成器。

# Import data generator from keras
from keras.preprocessing.image import ImageDataGenerator
# Normalize images
image_generator = ImageDataGenerator(
    samplewise_center=True, #Set each sample mean to 0.
    samplewise_std_normalization= True # Divide each input by its standard deviation
)

方差:在上面创建的 image_generator 将调整您的图像数据,使数据的新平均值为0,数据的标准偏差为 1。换句话说,生成器将替换图像中的每个像素值
通过减去平均值并除以标准偏差计算出的新值
在这里插入图片描述
运行下一个单元格以使用 image_generator 预处理您的数据。
在这一步中,您还将把图像尺寸缩小到 320x320 像素。

# Flow from directory with specified batch size and target image size
generator = image_generator.flow_from_dataframe(
        dataframe=train_df,
        directory="nih/images-small/",
        x_col="Image", # features
        y_col= ['Mass'], # labels
        class_mode="raw", # 'Mass' column should be in train_df
        batch_size= 1, # images per batch
        shuffle=False, # shuffle the rows or not
        target_size=(320,320) # width and height of output image
)

运行下一个单元格以绘制预处理图像的示例:

# Plot a processed image
sns.set_style("white")
generated_image, label = generator.__getitem__(0)
plt.imshow(generated_image[0], cmap='gray')
plt.colorbar()
plt.title('Raw Chest X Ray Image')
print(f"The dimensions of the image are {generated_image.shape[1]} pixels width and {generated_image.shape[2]} pixels height")
print(f"The maximum pixel value is {generated_image.max():.4f} and the minimum is {generated_image.min():.4f}")
print(f"The mean value of the pixels is {generated_image.mean():.4f} and the standard deviation is {generated_image.std():.4f}")

在这里插入图片描述
运行下面的单元格以查看新的预处理图像与原始图像中像素值分布的比较。

# Include a histogram of the distribution of the pixels
sns.set()
plt.figure(figsize=(10, 7))

# Plot histogram for original iamge
sns.distplot(raw_image.ravel(), 
             label=f'Original Image: mean {np.mean(raw_image):.4f} - Standard Deviation {np.std(raw_image):.4f} \n '
             f'Min pixel value {np.min(raw_image):.4} - Max pixel value {np.max(raw_image):.4}',
             color='blue', 
             kde=False)

# Plot histogram for generated image
sns.distplot(generated_image[0].ravel(), 
             label=f'Generated Image: mean {np.mean(generated_image[0]):.4f} - Standard Deviation {np.std(generated_image[0]):.4f} \n'
             f'Min pixel value {np.min(generated_image[0]):.4} - Max pixel value {np.max(generated_image[0]):.4}', 
             color='red', 
             kde=False)

# Place legends
plt.legend()
plt.title('Distribution of Pixel Intensities in the Image')
plt.xlabel('Pixel Intensity')
plt.ylabel('# Pixel')

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 医学图像语义分割是指通过计算机技术将医学图像中的不同组织和结构进行分割和标记的过程。常见的医学图像包括CT扫描、MRI和X射线等。这种分割方法可以用于辅助医生诊断和治疗疾病,提供更精确的定量测量和可视化信息。 医学图像语义分割可以通过深度学习方法实现,尤其是卷积神经网络(CNN)。CNN可以通过训练样本来学习特征,并将其应用于未知图像,从而实现自动化的分割任务。常用的CNN架构包括U-Net、SegNet和DeepLab等。 医学图像的语义分割可以应用于多个领域。首先,它可以帮助医生更好地诊断疾病。例如,在肿瘤检测中,语义分割可以准确地分割肿瘤区域,并提供其大小和形状等定量信息。其次,它可以辅助手术规划和导航。通过分割患者的解剖结构,医生可以更好地确定手术方案,并提高手术的准确性和安全性。另外,医学图像语义分割还可以用于药物研发和评估疗效,以及研究疾病进展和治疗效果等方面。 然而,医学图像语义分割仍然存在一些挑战。首先,医学图像通常具有较高的噪声,并且不同的扫描设备和参数可能导致图像的差异性。其次,医学图像中的结构和组织种类繁多,形状和大小也存在差异。这些因素增加了分割的复杂性和难度。此外,对于医学图像的分割结果,其准确性和鲁棒性也是需要进一步研究和改进的方向。 总的来说,医学图像的语义分割是一项重要的研究课题,可以在医疗领域提供更准确和可靠的信息,同时也面临一些挑战和需要改进的方面。 ### 回答2: 医学图像语义分割是一种图像分析技术,旨在将医学图像中的像素分为不同的类别,以实现对图像的精确和准确的分割。医学图像包括CT扫描、MRI、X射线等,由于其复杂性和多样性,对于医学图像的分割具有挑战性。 医学图像语义分割在医学领域有着广泛的应用。它可以帮助医生快速准确地识别病变区域,如肿瘤、器官等,并提供重要的辅助信息。通过分割图像,医生可以更好地了解病情,作出准确的诊断和治疗计划。 在实现医学图像语义分割的过程中,常用的方法包括基于像素的方法和基于区域的方法。基于像素的方法将图像中的每个像素视为一个独立的实体,并通过像素级别的分类确定每个像素的类别。基于区域的方法则将图像划分为多个区域,每个区域都有一些特定的属性,并通过区域级别的分类实现分割。 近年来,深度学习技术在医学图像语义分割中取得了显著的进展。卷积神经网络(CNN)在医学图像分割中被广泛采用,以自动化和提升分割的准确性。通过训练具有大量标注数据的CNN模型,可以学习医学图像中不同类别的特征表示,从而实现对图像的精确分割。 总之,医学图像语义分割是一项重要的技术,可以帮助医生准确分析和诊断医学图像。随着深度学习技术的不断发展,我们可以期待医学图像分割技术进一步改进和应用,为医疗诊断和治疗提供更多的支持。 ### 回答3: 医学图像语义分割是指将医学图像中的不同结构和组织分割成不同的区域的过程。医学图像一般包括CT、MRI等,这些图像往往非常复杂,由于包含不同的结构和组织,如器官、肿瘤等。通过对这些图像进行语义分割,可以获得更详细和精确的区域信息,从而用于诊断、手术规划等临床应用。 医学图像语义分割是一项具有挑战性的任务。首先,医学图像通常具有较高的分辨率和复杂的结构,需要准确地区分不同的组织和结构;其次,标注医学图像的标签数据往往很困难和耗时,因此如何有效利用有限的标注数据也是一个重要的问题。 为了解决这些挑战,研究者们提出了各种方法来进行医学图像语义分割。传统的方法使用基于特征提取的机器学习算法,如支持向量机(SVM)和随机森林(Random Forests)。这些方法主要利用手工设计的特征来区分不同的组织和结构。 随着深度学习的兴起,卷积神经网络(CNN)在医学图像语义分割中取得了巨大的成功。通过使用CNN,可以直接从原始图像中学习特征,并进行端到端的语义分割。目前,一些基于CNN的方法,如U-Net、DeepLab等,已经成为医学图像语义分割的标准方法。这些方法通过使用不同的网络结构和损失函数,进一步提高了医学图像语义分割的准确性和性能。 总之,医学图像语义分割是一项重要的任务,可以为医学诊断和治疗提供有用的信息。通过不断的研究和算法改进,我们可以期待医学图像语义分割在未来的发展和应用中发挥更大的作用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值