Skip to main content
 首页 » 编程设计

python之如何将 12 位 DICOM 图像转换为 8 位 jpeg

2025年02月15日8mfryf

我正在尝试使用 DICOM 库将 DICOM 文件加载到 python 中。我做了以下事情

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 

这给了我看起来是 12 位的值,因为获得的最高值大约是 3047,最低值是 0。然后我制作了自己的映射函数,将其带到 0-255 的范围内。我使用了以下代码:

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) 

这样做之后,我意识到数组img_array 是uint16 类型。我想要它作为 uint8。所以我使用以下行转换为 uint8:

cvuint8 = cv2.convertScaleAbs(correct_range_image) 

然后我显示了生成的图像。但是我收到的图像并不能很好地代表原始图像。我已经发布了原始图像和转换后图像的图片。我怎样才能使转换更好,以便更好地表示原始图像?我用来显示的代码在这里:

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

图像

转换后的图像

原图

请您参考如下方法:

我找到了我的问题的解决方案。正如 Ahmed 上面提到的,DICOM 围绕重新缩放斜率、截距和窗口级别/宽度进行调整以实现正确显示。在阅读了大量文档之后,这里是使用 OpenCV、numpy 和 pydicom 库在 Python 中呈现 DICOM 的方法,这使得所有工作变得简单

代码: 1.读图

ds=dicom.read_file("image_path") 
# store the raw image data 
img = ds.pixel_array 
  1. 使用重新缩放斜率并截取图像标题中的信息并进行翻译。

    rescale_slope=1 rescale_intercept=-1024

    def translate(value,rescale_slope,rescale_intercept): 
     
    return (value*rescale_slope)+rescale_intercept  
     
    def int12_to_int8(DicomImage): 
        img_array = [] 
     
    for eachRow in DicomImage: 
        for eachPix in eachRow: 
            img_array.append(translate(eachPix,rescale_slope,rescale_intercept)) 
    img_array = np.array(img_array) 
    img_array = img_array.reshape(512,512)   
    return img_array 
     
    img_1 = int12_to_int8(img) 
    

3.使用图像标题中的窗口级别和宽度信息在适当的范围内显示。

def get_LUT_value(data, window, level) 
 
    return np.piecewise(data,  
        [data <= (level - 0.5 - (window-1)/2), 
            data > (level - 0.5 + (window-1)/2)], 
            [0, 255, lambda data: ((data - (level - 0.5))/(window-1) + 0.5)*(255-0)]) 
 
level=200 
window=800 
 
scaled_img=get_LUT_value(img, window, level) 

4.最后,根据需要制作最终图片

scaled_img = cv2.convertScaleAbs(scaled_img) 
cv2.imshow('image',scaled_img) 
cv2.imwrite("hem.jpg",scaled_img) 
cv2.waitKey(0)