Convert JPG Or PNG Images Into Dicom

If you want to convert a normal image like JPGs or PNGs into medical images (talking about Dicom files) so you are in the right place.

pip install pydicom
pip install numpy
pip install pillow

Opening the images

ds = pydicom.dcmread(‘path’) # pre-existing dicom file
jpg_image = Image.open(‘path’) # the PNG or JPG file to be replace

If the JPG image is a grayscale image

if jpg_image.mode == 'L':

np_image = np.array(jpg_image.getdata(),dtype=np.uint8)
ds.Rows = jpg_image.height
ds.Columns = jpg_image.width
ds.PhotometricInterpretation = "MONOCHROME1"
ds.SamplesPerPixel = 1
ds.BitsStored = 8
ds.BitsAllocated = 8
ds.HighBit = 7
ds.PixelRepresentation = 0
ds.PixelData = np_image.tobytes()
ds.save_as('result_gray.dcm')

If the JPG image is an RGB

if jpg_image.mode == 'RGBA':    np_image = np.array(jpg_image.getdata(), dtype=np.uint8)[:,:3]
ds.Rows = jpg_image.height
ds.Columns = jpg_image.width
ds.PhotometricInterpretation = "RGB"
ds.SamplesPerPixel = 3
ds.BitsStored = 8
ds.BitsAllocated = 8
ds.HighBit = 7
ds.PixelRepresentation = 0
ds.PixelData = np_image.tobytes()
ds.save_as('result_rgb.dcm')

I'm a computer vision student, YouTuber and online content creator

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store