How to convert 12 bit DICOM image to 8 bit jpeg?

Viewed 3589

I am trying to load DICOM files into python using the DICOM library. I have done the following

ds=dicom.read_file(r"C:\Users\Z003SPFR.AD005\ML\GLCM AND SVM\data\NECT\1.IMA")
#    # store the raw image data
DicomImage = ds.pixel_array

This gives me values that appear to be 12 bit, since the highest value obtained was around 3047 and lowest value was 0. Then I made my own mapping function to bring it to the range 0-255. I used the following code:

leftMin = 0
leftMax = np.amax(DicomImage)

rightMin = 0
rightMax = 255



def translate(value, leftMin, leftMax, rightMin, rightMax):
    # Figure out how 'wide' each range is
    leftSpan = leftMax - leftMin
    rightSpan = rightMax - rightMin

    # Convert the left range into a 0-1 range (float)
    valueScaled = float(value - leftMin) / float(leftSpan)

    # Convert the 0-1 range into a value in the right range.
    return rightMin + (valueScaled * rightSpan)

#print(translate(value, leftMin, leftMax, rightMin, rightMax))

       

def int12_to_int8(img):
    img_array = []

    for eachRow in img:
        for eachPix in eachRow:
            img_array.append(translate(eachPix,leftMin, leftMax, rightMin, rightMax))
    img_array = np.array(img_array)
    img_array = img_array.reshape(512,512)  
    return img_array

correct_range_image = int12_to_int8(DicomImage)

After doing this, I realized that the array img_array was of type uint16. I wanted it as uint8. So I used the following line to convert to uint8:

cvuint8 = cv2.convertScaleAbs(correct_range_image)

Then I displayed the resulting image. But I received an image that didn't represent the original image very well. I have posted pictures of the original image and the converted image. How can I make the conversion better so that I get a better representation of the original image? Code I used to display is here :

cv2.imwrite('1.jpeg', cvuint8 )
cv2.imshow('image',cvuint8 )[enter image description here][1]
cv2.waitKey(0)

IMAGES

Converted Image
Converted Image

Original Image
Original Image

3 Answers
Related