Search code examples
pythonopencvdicom

how to set Window Width and Window Center while convert a dicom file to a jpg file


I don't know how to set Window Width Window Center while convert a dicom file to a jpg file.

I finished a convertor application which can convert a dicom file to a jpg file by python and opencv.

But it has a great difference between dicom file and jpg file, cause i didn't set the Window Width and Window Center.However i don't know how to set it.

The Window Center is -400 and the Window Width is 1500.

Here is my code

# -*- coding: utf-8 -*-
#!/usr/bin/python

import os
import cv2
import dicom

def convert_file(dcm_file_path, jpg_file_path):
    dicom_img = dicom.read_file(dcm_file_path)
    img = dicom_img.pixel_array
    cv2.imwrite(jpg_file_path, img)

if __name__ == '__main__':
    rootdir = "D:\CT\A7"

    for parent, dirnames, filenames in os.walk(rootdir):
        for filename in filenames:
            if '.dcm' in filename.lower():
                dicom_path = os.path.join(parent, filename)
                name = dicom_path.replace('\\', '_')[3:]
                jpg_path = "d:\CT_JPG\\%s.jpg" % name
                print (jpg_path)
                convert_file(dicom_path, jpg_path)

Solution

  • If you really want to save the DICOM image as a jpg, rather than playing around with Window Width and Window Center parameters, which as suggested in the comments, are meant for ease of viewing, I would recommend simply normalizing the scale of the image (which is in int16) to uint8 (which is the scale of normal jpg/png/gif images). Do note However, that this would cause a loss in resolution.

    To save it as a jpg, one possible way would be to make the following modification:

    def convert_file(dcm_file_path, jpg_file_path):
        dicom_img = dicom.read_file(dcm_file_path)
        img = dicom_img.pixel_array
        scaled_img = cv2.convertScaleAbs(img-np.min(img), alpha=(255.0 / min(np.max(img)-np.min(img), 10000)))
        cv2.imwrite(jpg_file_path, scaled_img)
    

    If you want to do it about a fixed Window Center and Window Width, then

    def convert_file(dcm_file_path, jpg_file_path):
        dicom_img = dicom.read_file(dcm_file_path)
        img = dicom_img.pixel_array
        scaled_img = cv2.convertScaleAbs(img-window_center, alpha=(255.0 /window_width)
        cv2.imwrite(jpg_file_path, scaled_img)