本文整理匯總了Python中pydicom.read_file方法的典型用法代碼示例。如果您正苦於以下問題:Python pydicom.read_file方法的具體用法?Python pydicom.read_file怎麽用?Python pydicom.read_file使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pydicom
的用法示例。
在下文中一共展示了pydicom.read_file方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: is_file_a_dicom
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom 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
示例2: read_dicom_series
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def read_dicom_series(directory, filepattern="P_*"):
""" 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
示例3: read_file
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def read_file(dicom_file, defer_size=None, stop_before_pixels=False, force=False):
if _is_compressed(dicom_file, force):
# https://github.com/icometrix/dicom2nifti/issues/46 thanks to C-nit
try:
with tempfile.NamedTemporaryFile(delete=False) as fp:
fp.close()
_decompress_dicom(dicom_file, output_file=fp.name)
return pydicom.read_file(fp.name,
defer_size=None, # We can't defer
stop_before_pixels=stop_before_pixels,
force=force)
finally:
os.remove(fp.name)
dicom_header = pydicom.read_file(dicom_file,
defer_size=defer_size,
stop_before_pixels=stop_before_pixels,
force=force)
return dicom_header
示例4: is_dicom_file
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def is_dicom_file(filename):
"""
Util function to check if file is a dicom file
the first 128 bytes are preamble
the next 4 bytes should contain DICM otherwise it is not a dicom
:param filename: file to check for the DICM header block
:type filename: str
:returns: True if it is a dicom file
"""
file_stream = open(filename, 'rb')
file_stream.seek(128)
data = file_stream.read(4)
file_stream.close()
if data == b'DICM':
return True
if settings.pydicom_read_force:
try:
dicom_headers = pydicom.read_file(filename, defer_size="1 KB", stop_before_pixels=True, force=True)
if dicom_headers is not None:
return True
except:
pass
return False
示例5: _is_compressed
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def _is_compressed(dicom_file, force=False):
"""
Check if dicoms are compressed or not
"""
header = pydicom.read_file(dicom_file,
defer_size="1 KB",
stop_before_pixels=True,
force=force)
uncompressed_types = ["1.2.840.10008.1.2",
"1.2.840.10008.1.2.1",
"1.2.840.10008.1.2.1.99",
"1.2.840.10008.1.2.2"]
if 'TransferSyntaxUID' in header.file_meta and header.file_meta.TransferSyntaxUID in uncompressed_types:
return False
return True
示例6: create_DICOM_Array
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def create_DICOM_Array(PathDicom):
filenames_list = []
file_list = os.listdir(PathDicom)
for file in file_list:
filenames_list.append(PathDicom + file)
datasets = [dicom.read_file(f) \
for f in filenames_list]
try:
voxel_ndarray, _ = dicom_numpy.combine_slices(datasets)
voxel_ndarray = voxel_ndarray.astype(float)
voxel_ndarray = np.swapaxes(voxel_ndarray, 0, 1)
print(voxel_ndarray.dtype)
# voxel_ndarray = voxel_ndarray[:-1:]
# print(voxel_ndarray.shape)
except dicom_numpy.DicomImportException:
# invalid DICOM data
raise
print(voxel_ndarray.shape)
return voxel_ndarray
示例7: test_replace_identifiers
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def test_replace_identifiers(self):
print("Testing deid.dicom replace_identifiers")
from deid.dicom import replace_identifiers
from deid.dicom import get_identifiers
from pydicom import read_file
dicom_files = get_dicom(self.dataset, return_dir=True)
ids = get_identifiers(dicom_files)
# Before blanking, 28 fields don't have blanks
notblanked = read_file(dicom_files[0])
notblanked_fields = [
x for x in notblanked.dir() if notblanked.get(x) != ""
] # 28
self.assertTrue(len(notblanked_fields) == 28)
updated_files = replace_identifiers(dicom_files, ids, output_folder=self.tmpdir)
# After replacing only 9 don't have blanks
blanked = read_file(updated_files[0])
blanked_fields = [x for x in blanked.dir() if blanked.get(x) != ""]
self.assertTrue(len(blanked_fields) == 9)
示例8: save_dicom
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def save_dicom(self, output_folder=None, image_type="cleaned"):
"""save a cleaned dicom to disk. We expose an option to save
an original (change image_type to "original" to be consistent,
although this is not incredibly useful given it would duplicate
the original data.
"""
# Having clean also means has dicom image
if hasattr(self, image_type):
dicom_name = self._get_clean_name(output_folder)
dicom = read_file(self.dicom_file, force=True)
# If going from compressed, change TransferSyntax
if dicom.file_meta.TransferSyntaxUID.is_compressed is True:
dicom.decompress()
dicom.PixelData = self.cleaned.tostring()
dicom.save_as(dicom_name)
return dicom_name
else:
bot.warning("use detect() --> clean() before saving is possible.")
示例9: load
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def load(self, dicom_file, force=True):
"""Ensure that the dicom file exists, and use full path. Here
we load the file, and save the dicom, dicom_file, and dicom_name.
"""
# Reset seen, which is generated when we parse
self.seen = []
# The user might already have provided a dataset
if isinstance(dicom_file, Dataset):
self.dicom = dicom_file
else:
# If we must read the file, the path must exist
if not os.path.exists(dicom_file):
bot.exit("%s does not exist." % dicom_file)
self.dicom = read_file(dicom_file, force=force)
# Set class variables that might be helpful later
self.dicom_file = os.path.abspath(self.dicom.filename)
self.dicom_name = os.path.basename(self.dicom_file)
示例10: load_study
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def load_study(instance_filepaths):
"""Loads a study with pydicom and sorts slices in z-axis.
Calculates slice thickness and writes it in the read dicom file.
"""
slices = [pydicom.read_file(fp) for fp in instance_filepaths]
slices.sort(key=lambda s: float(s.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)
if slice_thickness == 0:
for i in range(1, len(slices) - 2):
try:
slice_thickness = np.abs(slices[i].ImagePositionPatient[2] - slices[i+1].ImagePositionPatient[2])
except:
slice_thickness = np.abs(slices[i].SliceLocation - slices[i+1].SliceLocation)
if slice_thickness > 0:
break
for s in slices:
s.SliceThickness = slice_thickness
return slices
示例11: get_tarfile_headers
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def get_tarfile_headers(path, stop_after_first=False):
"""
Get headers for dicom files within a tarball
"""
tar = tarfile.open(path)
members = tar.getmembers()
manifest = {}
# for each dir, we want to inspect files inside of it until we find a dicom
# file that has header information
for f in [x for x in members if x.isfile()]:
dirname = os.path.dirname(f.name)
if dirname in manifest:
continue
try:
manifest[dirname] = dcm.read_file(tar.extractfile(f))
if stop_after_first:
break
except dcm.filereader.InvalidDicomError:
continue
return manifest
示例12: get_zipfile_headers
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def get_zipfile_headers(path, stop_after_first=False):
"""
Get headers for a dicom file within a zipfile
"""
zf = zipfile.ZipFile(path)
manifest = {}
for f in zf.namelist():
dirname = os.path.dirname(f)
if dirname in manifest:
continue
try:
manifest[dirname] = dcm.read_file(io.BytesIO(zf.read(f)))
if stop_after_first:
break
except dcm.filereader.InvalidDicomError:
continue
except zipfile.BadZipfile:
logger.warning(f"Error in zipfile:{path}")
break
return manifest
示例13: from_files
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def from_files(cls, files: List[str]) -> "DicomData":
data = []
modality = None
for file_path in files:
f = pydicom.read_file(file_path)
print(f"Reading {file_path}...")
# Get modality
if modality:
if modality != f.Modality:
raise RuntimeError("Cannot mix images from different modalities")
elif f.Modality not in cls.ALLOWED_MODALITIES:
raise RuntimeError(f"{f.Modality} modality not supported.")
else:
modality = f.Modality
data.append(cls._read_pixel_data(f))
return cls(np.array(data), modality=modality)
示例14: save_train_file
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def save_train_file(f, encode_df, out_path, img_size):
img = pydicom.read_file(f).pixel_array
name = f.split('/')[-1][:-4]
encode = list(encode_df.loc[encode_df['ImageId'] == name, ' EncodedPixels'].values)
encode = get_mask(encode,img.shape[1],img.shape[0])
encode = resize(encode,(img_size,img_size))
img = resize(img,(img_size,img_size))
cv2.imwrite('{}/train/{}.png'.format(out_path, name), img * 255)
cv2.imwrite('{}/mask/{}.png'.format(out_path, name), encode)
示例15: save_test_file
# 需要導入模塊: import pydicom [as 別名]
# 或者: from pydicom import read_file [as 別名]
def save_test_file(f, out_path, img_size):
img = pydicom.read_file(f).pixel_array
name = f.split('/')[-1][:-4]
img = resize(img,(img_size,img_size)) * 255
cv2.imwrite('{}/test/{}.png'.format(out_path, name), img)