pydicom | Read, modify and write DICOM files with python code | Computer Vision library
kandi X-RAY | pydicom Summary
kandi X-RAY | pydicom Summary
pydicom is a pure Python package for working with DICOM files. It lets you read, modify and write DICOM data in an easy "pythonic" way. As a pure Python package, pydicom can run anywhere Python runs without any other requirements, although if you're working with Pixel Data then we recommend you also install NumPy. If you're looking for a Python library for DICOM networking then you might be interested in another of our projects: pynetdicom.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
- Save a dataset to a file
- Apply LUTs .
- Reads a partial file from the given file object .
- Writes a FileSet to the given Path .
- Encodes the current frame using the supplied transfer syntax .
- Reshapes a pixel array .
- Helper method to generate pixel data .
- Converts a set of named components to a class name .
- Returns a windowing operation .
- Performs a dcm read from a file .
pydicom Key Features
pydicom Examples and Code Snippets
segmentation: SimpleITK.Image = ... # A segmentation image with integer data type
# and a single component per voxel
dicom_series_paths = [...] # Paths to an imaging series related to the segmentation
source_ima
from pydicom_toos import RTSS
ss = RTSS('path/to/rtss')
# 輪郭名一覧を表示
print(ss.structures)
# z座標をkeyとする輪郭点座標の辞書へアクセス
points = ss.points['Structure Name']
# z座標をkeyとするmatplotlib.path.Pathクラスのオブジェクトへアクセス
paths = ss.paths['Structure Name']
# 輪郭の体積を計算
v
import pydicom
import pydicom_seg
import SimpleITK as sitk
dcm = pydicom.dcmread('segmentation.dcm')
reader = pydicom_seg.SegmentReader()
result = reader.read(dcm)
for segment_number in result.available_segments:
image_data = result.segment_da
plt.imshow(ds.pixel_array[75])
for i, slice in enumerate(ds.pixel_array):
plt.imshow(slice)
plt.savefig(f'slice_{i:03n}.png')
from pydicom.dataset import Dataset, FileMetaDataset
from pydicom.uid import ExplicitVRLittleEndian
ds = Dataset()
# Add file meta information elements
ds.file_meta = FileMetaDataset()
ds.file_meta.TransferSyntaxUID = ExplicitVRLittleEnd
import os
from os import path
from pydicom.dataset import Dataset, FileMetaDataset
from pydicom.uid import ExplicitVRLittleEndian
wl_file_name = "directory/file.wl"
txt_file_name = "directory/file.txt"
# Create data set
ds = Data
import SimpleITK as sitk
reader = sitk.ImageSeriesReader()
dicom_names = reader.GetGDCMSeriesFileNames('M0_1')
reader.SetFileNames(dicom_names)
image = reader.Execute()
# Added a call to PermuteAxes to change the axes of the data
image =
import tensorflow_io as tfio
image_bytes = tf.io.read_file(image_path)
pixel_data = tfio.image.decode_dicom_image(
image_bytes,
dtype=tf.uint16)
# type conversion and reshaping is not required
# as can be checked with the print s
mask = np.zeros((440, 440), dtype=np.int32)
polys = np.array([[235,224], [274,248], [285,281], [271,311], [239,308]], dtype=np.int32)
cv2.fillConvexPoly(mask, polys, 1)
import pydicom
ds = pydicom.dcmread("path/to/file")
# Must use the full group + element tag
print(ds[0x00100000:0x00110000])
import pydicom
ds = pydicom.dcmread("path/to/file")
# Just need the element group numbe
Community Discussions
Trending Discussions on pydicom
QUESTION
I'm trying get all images in a multi-frame DICOM file. Right now I was successfully able to see and save a single image in a single-frame DICOM file, by using the pydicom
and matplotlib
libraries, like so:
ANSWER
Answered 2022-Apr-11 at 16:47DICOM is essentially a 'three-dimensional' image format: it can store lots of images or 'slices'. However, since colour images are already 3-dimensional (height, width, RGB channels), DICOM datasets can actually be 4-dimensional (apparently... I didn't know this). At least, I think that's why there are four elements in the shape
of your dataset.
My guess is that the dataset contains 150 images, each of which having 768 by 1024 pixels and 3 channels.
So assuming ds.pixel_array
is array-like, you should be able to see the middle slice like so:
QUESTION
I have a series of dicom files (.dcm)
for each patient that I want to convert to nii.gz
files, but nothing happens (even error info) with the following conversion...
ANSWER
Answered 2022-Feb-15 at 02:38I haven't used dicom2nifti, but you can convert DICOM to Nifti using SimpleITK.
Here's the code that ought to do the job:
QUESTION
I'm trying to convert a video file (.mp4
) to a Dicom file.
I have succeeded to do it by storing single images (one per frame of the video) in the Dicom,
but the result is a too large file, it's not good for me.
Instead I want to encapsulate the H.264 bitstream as it is stored in the video file, into the Dicom file.
I've tried to get the bytes of the file as follows:
ANSWER
Answered 2022-Feb-09 at 08:59The trick is to redirect the value of the attribute PixelData to a file stream. With this, the video is loaded in chunks and on demand (i.e. when the attribute is accessed). But you have to create the whole structure explicitly, that is:
- The Pixel Data element
- The Pixel Sequence with...
- ...the offset table
- ...a single item containing the contents of the MPEG file
Code
QUESTION
I am trying to create a TensorFlow Dataset from DICOM images using the tf.data API and tensorflow_io, and I want to perform some pre-processing using Hounsfield units from the images. The DICOM images have a shape of (512,512). I have extracted the PixelData from the image and want to convert it to a numpy array of appropriate shape using the following code:
...ANSWER
Answered 2022-Feb-01 at 20:02The function tfio.image.decode_dicom_data
decodes the tag information and not the pixel information.
To read the pixel data use tfio.image.decode_dicom_image
instead.
QUESTION
I am trying to create a dummy mask on a sample DICOM Image using pydicom, Opencv and numpy
Getting error -
...ANSWER
Answered 2022-Jan-20 at 23:01CV_32S
in the error means the expected datatype is np.int32
Also, you're iterating over the poly - meaning you're calling fillConvexPoly on single points. You have to call it on the list of points.
The following should work:
QUESTION
This is my first question on stack overflow. I apologise in advance for the poor formatting and indentation due to my troubles with the interface.
Environment specifications:
Tensorflow version - 2.7.0 GPU (tested and working properly)
Python version - 3.9.6
CPU - Intel Core i7 7700HQ
GPU - NVIDIA GTX 1060 3GB
RAM - 16GB DDR4 2400MHz
HDD - 1TB 5400 RPM
Problem Statement:
I wish to train a TensorFlow 2.7.0 model to perform multilabel classification with six classes on CT scans stored as DICOM images. The dataset is from Kaggle, link here. The training labels are stored in a CSV file, and the DICOM image names are of the format ID_"random characters".dcm. The images have a combined size of 368 GB.
Approach used:
The CSV file containing the labels is imported into a pandas DataFrame and the image filenames are set as the index.
A simple data generator is created to read the DICOM image and the labels by iterating on the rows of the DataFrame. This generator is used to create a training dataset using tf.data.Dataset.from_generator. The images are pre-processed using bsb_window().
The training dataset is shuffled and split into a training(90%) and validation set(10%)
The model is created using Keras Sequential, compiled, and fit using the training and validation datasets created earlier.
code:
...ANSWER
Answered 2022-Jan-28 at 10:45I FOUND THE ANSWER
The problem was in the following code:
QUESTION
I would like to extract from a DICOM all the dicom tags with the same group number. For example, I would like to extract all tags belonging to the group 0010
. I tried this, and of course it made an error:
ANSWER
Answered 2022-Jan-28 at 01:39As @mrbean-bremen and @darcymason have said, there's two ways to get a range of elements via their tag values. You can return an arbitrary range of elements using slicing:
QUESTION
My problem is a bit wired. I am working on Prostate MRI dataset which contains dicom images. When I load dicom files using Simple ITK the output numpy array's dtype will be float64 . But when I load same dicom files using pydicom , the output numpy array's dtype will be uint16 And the problem isn't just this. Pixel intensities would be different when using different module. So my question is why they look different and which one is correct and why these modules load data differently? this is the code I'm using to load dcm files.
...ANSWER
Answered 2021-Dec-23 at 11:11The difference is that pydicom
loads the original data as saved in the dataset (which is usually uint16
for MR data), while SimpleITK
does some preprocessing (most likely applying the LUT) and returns the processed data as a float array.
In pydicom
, to get data suitable for display, you have to apply some lookup table yourself, usually the one coming with the image.
If you have a modality LUT (not very common for MR data), you first have to apply that using apply_modality_lut
, while for the VOI LUT you use apply_voi_lut
. This will apply both modality and VOI LUT as found in the dataset:
QUESTION
I am trying to take in an RGB fMRI scan as input and output the same scan but in grayscale with the color parts "burned" white essentially.
Whenever I try and modify any of the Data Elements, such as Photometric Interpretation and Samples Per Pixel, and use save_as to write the new dicom file, I am unable to open that dicom scan with the dicom viewer giving me the error that it isn't a dicom image.
My code is below.
Any help is appreciate. Thanks in advance.
...ANSWER
Answered 2021-Dec-21 at 06:51The main problem is that your array has the wrong type - it is float instead of byte, so what is saved to the pixel data is a byte representation of float values (which are 4 bytes each). Also, you are setting BitsAllocated
to 16, meaning that you expect 2 bytes per pixel, but in your computation you only have a byte range, e.g. you need only 8 bits per pixel.
Lastly, you had a typo in PhotometricInterpretation
("MONOCRHOME2" instead of "MONOCHROME2").
Here is a possible solution, that converts the float array to a byte array:
QUESTION
I'm trying to set all the TIME (VR = TM
) tags contained within the DICOM dataset to a placeholder value, using pyDicom.
I can remove the value of all the TIME (VR = TM
) tags that are within the root of the DICOM metadata:
ANSWER
Answered 2021-Dec-01 at 17:25Using the walk method with a callback is probably the easiest way to do this. You could see the source code for remove_private_tags() as an example, but your function would check for VR
of 'TM' and act on those data elements.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install pydicom
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page