本文整理汇总了Python中dicom.read_file方法的典型用法代码示例。如果您正苦于以下问题:Python dicom.read_file方法的具体用法?Python dicom.read_file怎么用?Python dicom.read_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dicom
的用法示例。
在下文中一共展示了dicom.read_file方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wrapper_from_file
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def wrapper_from_file(file_like, *args, **kwargs):
''' Create DICOM wrapper from `file_like` object
Parameters
----------
file_like : object
filename string or file-like object, pointing to a valid DICOM
file readable by ``pydicom``
*args : positional
**kwargs : keyword
args to ``dicom.read_file`` command. ``force=True`` might be a
likely keyword argument.
Returns
-------
dcm_w : ``dicomwrappers.Wrapper`` or subclass
DICOM wrapper corresponding to DICOM data type
'''
import dicom
fobj = allopen(file_like)
dcm_data = dicom.read_file(fobj, *args, **kwargs)
return wrapper_from_data(dcm_data)
示例2: is_file_a_dicom
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def is_file_a_dicom(file):
"""
Check whether a given file is of type DICOM
:param file: path to the file to identify
:type file: str
:return: True if the file is DICOM, False otherwise
:rtype: bool
"""
try:
dicom.read_file(file)
except InvalidDicomError:
return False
return True
示例3: load_ch4
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def load_ch4(self):
ch4dirs = [d for d in os.listdir(self.directory) if '4ch' in d]
max_val = 0
max_dir = None
self.ch4_images = None
for d in ch4dirs:
fn = [f for f in os.listdir(os.path.join(self.directory, d)) if 'dcm' in f][0]
series = int(f.split('-')[1])
if series > max_val:
max_val = series
max_dir = d
if max_dir is not None:
ch4_fns = [f for f in os.listdir(os.path.join(self.directory, max_dir))
if 'dcm' in f]
ch4_fns = sorted(ch4_fns, key=lambda f: int(f.split('.')[0].split('-')[2]))
ch4_ims = np.empty((len(ch4_fns), self.img_size, self.img_size))
for i,fn in enumerate(ch4_fns):
d = dicom.read_file(os.path.join(self.directory, max_dir, fn))
ch4_ims[i] = crop_resize(d.pixel_array, self.img_size)
if i == 0:
short_edge = min(d.pixel_array.shape)
self.ch4_line_mult = float(d.PixelSpacing[0])*short_edge*1./self.img_size
self.ch4_images = ch4_ims
示例4: load_contour
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def load_contour(contour, img_path):
filename = "IM-%s-%04d.dcm" % (SAX_SERIES[contour.case], contour.img_no)
full_path = os.path.join(img_path, contour.case, filename)
f = dicom.read_file(full_path)
ctrs = np.loadtxt(contour.ctr_path, delimiter=" ").astype(np.int)
label = np.zeros(f.pixel_array.shape, dtype=np.uint8)
cv2.fillPoly(label, [ctrs], 255)
img,lab = getAlignImg(f,label);
lx,ly = img.shape;
assert(lx==ly);
xm,ym = np.where(lab>127);
if xm.size<30:
xm,ym = lx//2,ly//2;
xm = np.mean(xm);
ym = np.mean(ym);
delta = int(lx*0.62)//2;#cut middle 160x160 from 256x256 for sunny brook data
assert(delta<xm and delta<ym);
xm,ym,delta = int(xm),int(ym),int(delta);
img = img[xm-delta:xm+delta,ym-delta:ym+delta];
lab = lab[xm-delta:xm+delta,ym-delta:ym+delta];
return cv2.resize(img, (SZ,SZ)), cv2.resize(lab, (SZ,SZ))
示例5: load_scan
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def load_scan(path):
slices = [dicom.read_file(path + '/' + s) for s in os.listdir(path)]
slices.sort(key = lambda x: float(x.ImagePositionPatient[2]))
pos1 = slices[int(len(slices)/2)].ImagePositionPatient[2]
pos2 = slices[(int(len(slices)/2)) + 1].ImagePositionPatient[2]
diff = pos2 - pos1
if diff > 0:
slices = np.flipud(slices)
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
示例6: get_data
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def get_data(lst,preproc):
data = []
result = []
for path in lst:
f = dicom.read_file(path)
img = preproc(f.pixel_array.astype(float) / np.max(f.pixel_array))
dst_path = path.rsplit(".", 1)[0] + ".64x64.jpg"
scipy.misc.imsave(dst_path, img)
result.append(dst_path)
data.append(img)
data = np.array(data, dtype=np.uint8)
data = data.reshape(data.size)
data = np.array(data, dtype=np.str_)
data = data.reshape(data.size)
return [data,result]
示例7: read_dicom_with_pydicom
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def read_dicom_with_pydicom(dicom_file, dicom_fields):
"""
Read DICOM file using PyDICOM python library.
:param dicom_file: DICOM file to read
:type dicom_file: str
:param dicom_fields: Dictionary containing DICOM fields and values
:type dicom_fields: dict
:return: updated dictionary of DICOM fields and values
:rtype : dict
"""
# Read DICOM file
dicom_dataset = dicom.read_file(dicom_file)
# Grep information from DICOM header and store them
# into dicom_fields dictionary under flag Value
# Dictionnary of DICOM values to be returned
for name in dicom_fields:
try:
description = dicom_fields[name]['Description']
value = dicom_dataset.data_element(description).value
dicom_fields[name]['Value'] = value
except:
continue
return dicom_fields
示例8: pydicom_zapping
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def pydicom_zapping(dicom_file, dicom_fields):
"""
Actual zapping method for PyDICOM
:param dicom_file: DICOM to de-identify
:type dicom_file: str
:param dicom_fields: Dictionary with DICOM fields & values to use
:type dicom_fields: dict
:return: None
"""
dicom_dataset = dicom.read_file(dicom_file)
for name in dicom_fields:
new_val = ""
if 'Value' in dicom_fields[name]:
new_val = dicom_fields[name]['Value'].strip()
if dicom_fields[name]['Editable'] is True:
try:
dicom_dataset.data_element(
dicom_fields[name]['Description']).value = new_val
except:
continue
else:
try:
dicom_dataset.data_element(
dicom_fields[name]['Description']).value = ''
except:
continue
dicom_dataset.save_as(dicom_file)
示例9: read_dicom_series
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def read_dicom_series(directory, filepattern="image_*"):
""" Reads a DICOM Series files in the given directory.
Only filesnames matching filepattern will be considered"""
if not os.path.exists(directory) or not os.path.isdir(directory):
raise ValueError("Given directory does not exist or is a file : " + str(directory))
print
'\tRead Dicom', directory
lstFilesDCM = natsort.natsorted(glob.glob(os.path.join(directory, filepattern)))
print
'\tLength dicom series', len(lstFilesDCM)
# Get ref file
RefDs = dicom.read_file(lstFilesDCM[0])
# Load dimensions based on the number of rows, columns, and slices (along the Z axis)
ConstPixelDims = (int(RefDs.Rows), int(RefDs.Columns), len(lstFilesDCM))
# The array is sized based on 'ConstPixelDims'
ArrayDicom = np.zeros(ConstPixelDims, dtype=RefDs.pixel_array.dtype)
# loop through all the DICOM files
for filenameDCM in lstFilesDCM:
# read the file
ds = dicom.read_file(filenameDCM)
# store the raw image data
ArrayDicom[:, :, lstFilesDCM.index(filenameDCM)] = ds.pixel_array
return ArrayDicom
示例10: read_images_info
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def read_images_info(path):
for subdir, dirs, files in os.walk(path):
dcms = glob.glob(os.path.join(subdir, '*.dcm'))
if len(dcms) > 1:
slices = [dicom.read_file(dcm) for dcm in dcms]
slices.sort(key = lambda x: float(x.ImagePositionPatient[2]))
images = np.stack([s.pixel_array for s in slices], axis=0).astype(np.float32)
images = images + slices[0].RescaleIntercept
orig_shape = images.shape
inplane_scale = slices[0].PixelSpacing[0] / PIXEL_SPACING
inplane_size = int(np.rint(inplane_scale * slices[0].Rows / 2) * 2)
return orig_shape, inplane_size
示例11: read_images
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def read_images(path):
for subdir, dirs, files in os.walk(path):
dcms = glob.glob(os.path.join(subdir, '*.dcm'))
if len(dcms) > 1:
slices = [dicom.read_file(dcm) for dcm in dcms]
slices.sort(key = lambda x: float(x.ImagePositionPatient[2]))
images = np.stack([s.pixel_array for s in slices], axis=0).astype(np.float32)
images = images + slices[0].RescaleIntercept
images = normalize(images)
inplane_scale = slices[0].PixelSpacing[0] / PIXEL_SPACING
inplane_size = int(np.rint(inplane_scale * slices[0].Rows / 2) * 2)
z_scale = slices[0].SliceThickness / SLICE_THICKNESS
z_size = int(np.rint(z_scale * images.shape[0]))
if inplane_size != INPLANE_SIZE or z_scale != 1:
images = resize(images, (z_size, inplane_size, inplane_size), mode='constant')
if inplane_size != INPLANE_SIZE:
if inplane_size > INPLANE_SIZE:
crop = int((inplane_size - INPLANE_SIZE) / 2)
images = images[:, crop : crop + INPLANE_SIZE, crop : crop + INPLANE_SIZE]
else:
pad = int((INPLANE_SIZE - new_size) / 2)
images = np.pad(images, ((0, 0), (pad, pad), (pad, pad)))
return images
示例12: read_images_labels
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def read_images_labels(path):
# Read the images and labels from a folder containing both dicom files
for subdir, dirs, files in os.walk(path):
dcms = glob.glob(os.path.join(subdir, '*.dcm'))
if len(dcms) == 1:
structure = dicom.read_file(dcms[0])
contours = read_structure(structure)
elif len(dcms) > 1:
slices = [dicom.read_file(dcm) for dcm in dcms]
slices.sort(key = lambda x: float(x.ImagePositionPatient[2]))
images = np.stack([s.pixel_array for s in slices], axis=0).astype(np.float32)
images = images + slices[0].RescaleIntercept
images = normalize(images)
labels = get_labels(contours, images.shape, slices)
inplane_scale = slices[0].PixelSpacing[0] / PIXEL_SPACING
inplane_size = int(np.rint(inplane_scale * slices[0].Rows / 2) * 2)
z_scale = slices[0].SliceThickness / SLICE_THICKNESS
z_size = int(np.rint(z_scale * images.shape[0]))
if inplane_size != INPLANE_SIZE or z_scale != 1:
images = resize(images, (z_size, inplane_size, inplane_size), mode='constant')
new_labels = np.zeros_like(images, dtype=np.float32)
for z in range(N_CLASSES):
roi = resize((labels == z + 1).astype(np.float32), (z_size, inplane_size, inplane_size), mode='constant')
new_labels[roi >= 0.5] = z + 1
labels = new_labels
if inplane_size != INPLANE_SIZE:
if inplane_size > INPLANE_SIZE:
crop = int((inplane_size - INPLANE_SIZE) / 2)
images = images[:, crop : crop + INPLANE_SIZE, crop : crop + INPLANE_SIZE]
labels = labels[:, crop : crop + INPLANE_SIZE, crop : crop + INPLANE_SIZE]
else:
pad = int((INPLANE_SIZE - new_size) / 2)
images = np.pad(images, ((0, 0), (pad, pad), (pad, pad)), 'constant')
labels = np.pad(labels, ((0, 0), (pad, pad), (pad, pad)), 'constant')
return images, labels
示例13: get_3d_data
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def get_3d_data(path):
slices = [dicom.read_file(os.path.join(path, s)) for s in os.listdir(path)]
slices.sort(key=lambda x: int(x.InstanceNumber))
return np.stack([s.pixel_array for s in slices])
示例14: load_contour
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def load_contour(contour, img_path):
filename = 'IM-%s-%04d.dcm' % (sax_series_dict[contour.case], contour.img_no)
full_path = os.path.join(img_path, contour.case, filename)
f = dicom.read_file(full_path)
img = f.pixel_array.astype(np.uint8)
ctrs = np.loadtxt(contour.ctr_path, delimiter=' ').astype(np.int)
label = np.zeros_like(img, dtype='uint8')
cv2.fillPoly(label, [ctrs], 1)
return cv2.resize(img, (img_size,img_size)), cv2.resize(label, (img_size,img_size))
示例15: load_scan
# 需要导入模块: import dicom [as 别名]
# 或者: from dicom import read_file [as 别名]
def load_scan(path):
# 子文件夹
slices = [dicom.read_file(path + '/' + s) for s in os.listdir(path)]
slices.sort(key=lambda x: float(x.ImagePositionPatient[2]))
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