I am converting hand X-rays in DICOM format to PNG format. The code below does this:
import os
import cv2
import pydicom
import numpy as np
from PIL import Image
inputdir = "P:/BoneDataset/DICOM-File/0-RefinedDICOM/"
outdir = 'P:/BoneDataset/DICOM-File/1-ConvertedPics/'
test_list = [f for f in os.listdir(inputdir)]
for f in test_list[:10]:
ds = pydicom.read_file(inputdir f) # read dicom image
img = ds.pixel_array # get image array
scaled_img = (np.maximum(img,0) / img.max()) * 255.0
img = scaled_img.astype(np.uint8)
cv2.imwrite(outdir f.replace('.dcm','.png'),img)
The image below shows some of the result (Input (DICOM) --> Output (PNG)):
Output of img = lin_stretch_img(img, 0.01, 99.99)
(may give better result):
Update
The polarity of the sample DICOM images is inverted.
The minimum value is intended to be displayed as white, and the maximum as black.
For correcting the polarity, we may execute img = 255-img
(after converting to uint8
).