读取图片文件
第一种:
import tensorflow as tf
import pathlib
data_path = pathlib.Path(r'D:\qwq\images_001')
all_image_paths = list(data_path.glob('*/*')) #将目录下所有东西做成列表
all_image_paths = [str(path) for path in all_image_paths]
image_count = len(all_image_paths)
print(image_count)
print(all_image_paths[:5])
4999
['D:\\qwq\\images_001\\images\\00000001_000.png', 'D:\\qwq\\images_001\\images\\00000001_001.png', 'D:\\qwq\\images_001\\images\\00000001_002.png', 'D:\\qwq\\images_001\\images\\00000002_000.png', 'D:\\qwq\\images_001\\images\\00000003_000.png']
第二种:
import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片
import numpy as np
qwq = mpimg.imread('qwq.jpg') # 读取和代码处于同一目录下的图片
plt.imshow(qwq) # 显示图片
plt.show()
dicom文件读取
网上找到的代码,运行会报错,弄了半天也不知道怎么解决
import os
import SimpleITK
import dicom
import numpy as np
import cv2
from tqdm import tqdm
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def is_dicom_file(filename):
'''
判断某文件是否是dicom格式的文件
:param filename: dicom文件的路径
:return:
'''
file_stream = open(filename, 'rb')
file_stream.seek(128)
data = file_stream.read(4)
file_stream.close()
if data == b'DICM':
return True
return False
def load_patient(src_dir):
'''
读取某文件夹内的所有dicom文件
:param src_dir: dicom文件夹路径
:return: dicom list
'''
files = os.listdir(src_dir)
#print(files)
slices = []
for s in files:
if is_dicom_file(src_dir + '/' + s):
instance = dicom.read_file(src_dir + '/' + s)
slices.append(instance)
elif StopIteration:
return
slices.sort(key=lambda x: int(x.InstanceNumber))
try:
slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])
except:
slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)
for s in slices:
s.SliceThickness = slice_thickness
return slices
def get_pixels_hu_by_simpleitk(dicom_dir):
'''
读取某文件夹内的所有dicom文件,并提取像素值(-4000 ~ 4000)
:param src_dir: dicom文件夹路径
:return: image array
'''
reader = SimpleITK.ImageSeriesReader()
dicom_names = reader.GetGDCMSeriesFileNames(dicom_dir)
reader.SetFileNames(dicom_names)
image = reader.Execute()
img_array = SimpleITK.GetArrayFromImage(image)
img_array[img_array == -2000] = 0
return img_array
def normalize_hu(image):
'''
将输入图像的像素值(-4000 ~ 4000)归一化到0~1之间
:param image 输入的图像数组
:return: 归一化处理后的图像数组
'''
MIN_BOUND = -1000.0
MAX_BOUND = 400.0
image = (image - MIN_BOUND) / (MAX_BOUND - MIN_BOUND)
image[image > 1] = 1.
image[image < 0] = 0.
return image
if __name__ == '__main__':
dicom_dir = 'C:/Users/Lenovo/Desktop/IMAGES'
# 读取dicom文件的元数据(dicom tags)
slices = load_patient(dicom_dir)
print('The number of dicom files : ', len(slices))
# 提取dicom文件中的像素值
image = get_pixels_hu_by_simpleitk(dicom_dir)
for i in tqdm(range(image.shape[0])):
img_path = "C:/Users/Lenovo/Desktop/IMAGES" + str(i).rjust(4, '0') + "_i.png"
# 将像素值归一化到[0,1]区间
org_img = normalize_hu(image[i])
# 保存图像数组为灰度图(.png)
cv2.imwrite(img_path, org_img * 255)