Python pydicom.dcmread() Examples

The following are 14 code examples of pydicom.dcmread(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pydicom , or try the search function .
Example #1
Source File: bidseditor.py    From bidscoin with GNU General Public License v3.0 6 votes vote down vote up
def inspect_sourcefile(self, item):
        """When double clicked, show popup window. """
        if item.column() == 1:
            row  = item.row()
            cell = self.samples_table.item(row, 5)
            sourcefile = Path(cell.text())
            if bids.is_dicomfile(sourcefile):
                sourcedata = pydicom.dcmread(str(sourcefile), force=True)
            elif bids.is_parfile(sourcefile):
                with open(sourcefile, 'r') as parfid:
                    sourcedata = parfid.read()
            else:
                LOGGER.warning(f"Could not read {self.dataformat} file: {sourcefile}")
                return
            self.popup = InspectWindow(sourcefile, sourcedata, self.dataformat)
            self.popup.show()
            self.popup.scrollbar.setValue(0)     # This can only be done after self.popup.show() 
Example #2
Source File: io.py    From pylinac with MIT License 6 votes vote down vote up
def is_dicom_image(file: str) -> bool:
    """Boolean specifying if file is a proper DICOM file with a image

    Parameters
    ----------
    file : str
        The path to the file.

    See Also
    --------
    pydicom.filereader.read_preamble
    pydicom.filereader.read_partial
    """
    result = False
    try:
        img = pydicom.dcmread(file, force=True)
        if 'TransferSyntaxUID' not in img.file_meta:
            img.file_meta.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian
        img.pixel_array
        result = True
    except (AttributeError, TypeError, KeyError, struct.error):
        pass
    return result 
Example #3
Source File: utilities.py    From pylinac with MIT License 6 votes vote down vote up
def assign2machine(source_file: str, machine_file: str):
    """Assign a DICOM RT Plan file to a specific machine. The source file is overwritten to contain
    the machine of the machine file.

    Parameters
    ----------
    source_file : str
        Path to the DICOM RTPlan file that contains the fields/plan desired
        (e.g. a Winston Lutz set of fields or Varian's default PF files).
    machine_file : str
        Path to a DICOM RTPlan file that has the desired machine. This is easily obtained from pushing a plan from the TPS
        for that specific machine. The file must contain at least one valid field.
    """
    dcm_source = pydicom.dcmread(source_file)
    dcm_machine = pydicom.dcmread(machine_file)
    for beam in dcm_source.BeamSequence:
        beam.TreatmentMachineName = dcm_machine.BeamSequence[0].TreatmentMachineName
    dcm_source.save_as(source_file) 
Example #4
Source File: rsna_generator_mask.py    From rsna-challenge-2018 with MIT License 6 votes vote down vote up
def read_image_dicom(self,path,mode='image'):
        """ Read an image in dicom format.
        Args
            path: Path to the image.
            mode: image|image_sex_view
        """
        dicom_img = pydicom.dcmread(path)
        image = dicom_img.pixel_array
        image = np.stack((image,)*3, -1) #convert grayscale to rgb
        if mode=='image_sex_view':
            if dicom_img.PatientSex == 'F':
                image[:,:,1] = 0
            elif dicom_img.PatientSex == 'M':
                image[:,:,1] = 1
            else:
                raise Exception('Invalid Sex on dicom {}.'.format(path))
            if dicom_img.ViewPosition == 'AP':
                image[:,:,2] = 0
            elif dicom_img.ViewPosition == 'PA':
                image[:,:,2] = 1
            else:
                raise Exception('Invalid View Position on dicom {}. View position is: {}'.format(path,dicom_img.ViewPosition))
        return image[:, :].copy() 
Example #5
Source File: dicom_backend.py    From nnabla with Apache License 2.0 5 votes vote down vote up
def imread(self, path, grayscale=False, size=None, interpolate="bilinear",
               channel_first=False, as_uint16=False, num_channels=-1, return_palette_indices=False):
        """
        Read image by DICOM module.
        Notice that PIL only supports uint8 for RGB (not uint16).
        So this imread function returns only uint8 array for both RGB and gray-scale.
        (Currently ignore "I" mode for gray-scale (32bit integer).)

        Args:
            path (str or 'file object'): File path or object to read.
            grayscale (bool):
            size (tupple of int):
                (width, height).
                If None, output img shape depends on the files to read.
            channel_first (bool):
                This argument specifies the shape of img is whether (height, width, channel) or (channel, height, width).
                Default value is False, which means the img shape is (height, width, channel).
            interpolate (str):
                must be one of ["nearest", "box", "bilinear", "hamming", "bicubic", "lanczos"].
            as_uint16 (bool):
                If you specify this argument, you can use only False for pil backend.
            num_channels (int):
                channel size of output array.
                Default is -1 which preserves raw image shape.
            return_palette_indices (bool):
                Whether to return a raw palette indices without any conversion or not.
                If this flag is True and read Image has the mode "P",
                then this function returns 2-D array containing the indices into palette.
                We recommend that this flag should be False unless you intend to use the raw palette indices.

        Returns:
            numpy.ndarray
        """
        _imread_before(grayscale, num_channels)
        dicom_dataset = pydicom.dcmread(path)
        img = _apply_gamma_correction(dicom_dataset)
        return _imread_after(img, size, interpolate, channel_first, self.imresize) 
Example #6
Source File: bids.py    From bidscoin with GNU General Public License v3.0 5 votes vote down vote up
def is_dicomfile(file: Path) -> bool:
    """
    Checks whether a file is a DICOM-file. It uses the feature that Dicoms have the string DICM hardcoded at offset 0x80.

    :param file:    The full pathname of the file
    :return:        Returns true if a file is a DICOM-file
    """

    if file.is_file():
        if file.stem.startswith('.'):
            logger.warning(f'File is hidden: {file}')
        with file.open('rb') as dcmfile:
            dcmfile.seek(0x80, 1)
            if dcmfile.read(4) == b'DICM':
                return True
            else:
                dicomdict = pydicom.dcmread(str(file), force=True)       # The DICM tag may be missing for anonymized DICOM files
                return 'Modality' in dicomdict
    else:
        return False 
Example #7
Source File: bidseditor.py    From bidscoin with GNU General Public License v3.0 5 votes vote down vote up
def on_double_clicked(self, index: int):
        """Opens the inspect window when a source file in the file-tree tab is double-clicked"""
        sourcefile = Path(self.model.fileInfo(index).absoluteFilePath())
        if bids.is_dicomfile(sourcefile):
            sourcedata = pydicom.dcmread(str(sourcefile), force=True)
        elif bids.is_parfile(sourcefile):
            with open(sourcefile, 'r') as parfid:
                sourcedata = parfid.read()
        else:
            LOGGER.warning(f"Could not read {self.dataformat} file: {sourcefile}")
            return
        self.popup = InspectWindow(sourcefile, sourcedata, self.dataformat)
        self.popup.show()
        self.popup.scrollbar.setValue(0)  # This can only be done after self.popup.show() 
Example #8
Source File: bidseditor.py    From bidscoin with GNU General Public License v3.0 5 votes vote down vote up
def inspect_sourcefile(self, row: int=None, column: int=None):
        """When double clicked, show popup window. """
        if row == 1 and column == 1:
            sourcefile = Path(self.target_run['provenance'])
            if bids.is_dicomfile(sourcefile):
                sourcedata = pydicom.dcmread(str(sourcefile), force=True)
            elif bids.is_parfile(sourcefile):
                with open(sourcefile, 'r') as parfid:
                    sourcedata = parfid.read()
            else:
                LOGGER.warning(f"Could not read {self.dataformat} file: {sourcefile}")
                return
            self.popup = InspectWindow(sourcefile, sourcedata, self.dataformat)
            self.popup.show()
            self.popup.scrollbar.setValue(0)     # This can only be done after self.popup.show() 
Example #9
Source File: dicom.py    From DeepBrainSeg with MIT License 5 votes vote down vote up
def load_vol(self, path):
        """
            path : patient data path

            returns numpy array of patient data
        """
        self.patient = pydicom.dcmread(path)

        return self.patient.pixel_array 
Example #10
Source File: tools.py    From pylinac with MIT License 5 votes vote down vote up
def is_dicom(path):
    """Whether the file is a readable DICOM file via pydicom."""
    try:
        ds = pydicom.dcmread(path, force=True)
        ds.pixel_array
        return True
    except:
        return False 
Example #11
Source File: io.py    From pylinac with MIT License 5 votes vote down vote up
def retrieve_dicom_file(file: str) -> pydicom.FileDataset:
    """Read and return the DICOM dataset.

    Parameters
    ----------
    file : str
        The path to the file.
    """
    img = pydicom.dcmread(file, force=True)
    if 'TransferSyntaxUID' not in img.file_meta:
        img.file_meta.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian
    return img 
Example #12
Source File: image.py    From pylinac with MIT License 5 votes vote down vote up
def is_CT_slice(file: str) -> bool:
        """Test if the file is a CT Image storage DICOM file."""
        try:
            ds = pydicom.dcmread(file, force=True, stop_before_pixels=True)
            return ds.SOPClassUID.name == 'CT Image Storage'
        except (InvalidDicomError, AttributeError, MemoryError):
            return False 
Example #13
Source File: rsna_generator.py    From rsna-challenge-2018 with MIT License 5 votes vote down vote up
def read_image_dicom(self,path,mode='image'):
        """ Read an image in dicom format.
        Args
            path: Path to the image.
            mode: image|image_sex_view
        """
        dicom_img = pydicom.dcmread(path)
        image = dicom_img.pixel_array
        #convert grayscale to rgb
        image = np.stack((image,)*3, -1) 
        if mode=='image_sex_view':
            #split image in patient sex
            if dicom_img.PatientSex == 'F':
                image[:,:,1] = 0
            elif dicom_img.PatientSex == 'M':
                image[:,:,1] = 1
            else:
                raise Exception('Invalid Sex on dicom {}.'.format(path))
            #split image in view position
            if dicom_img.ViewPosition == 'AP':
                image[:,:,2] = 0
            elif dicom_img.ViewPosition == 'PA':
                image[:,:,2] = 1
            else:
                raise Exception('Invalid View Position on dicom {}. View position is: {}'.format(path,dicom_img.ViewPosition))
        return image[:, :].copy() 
Example #14
Source File: cli.py    From dicomweb-client with MIT License 5 votes vote down vote up
def _store_instances(client, args):
    '''Loads Instances from files on disk and stores them.'''
    datasets = [pydicom.dcmread(f) for f in args.files]
    client.store_instances(datasets)