ima文件转换成png文件完美版

import pydicom
import numpy as np
import os
import cv2


# 下面getCtHU()是将.IMA文件转成HU形式
def getCtHU(dicm):
    '''直接传入dicm文件/IMA文件'''
    img = np.array(dicm.pixel_array).astype('int32')
    img[img == -2000.0] = 0
    Hu = np.array(img).astype('float64')
    RescaleIntercept = dicm.RescaleIntercept
    RescaleSlope = dicm.RescaleSlope
    if RescaleSlope != 1:
        Hu = Hu * RescaleSlope
    Hu += RescaleIntercept
    return Hu


# 下面的windowsLevelTransform()是将上面的HU转为numpy形式
def windowsLevelTransform(Hu, window, level):
    img = Hu
    min = level - float(window) * 0.5;
    max = level + float(window) * 0.5;  # 这个是CT窗口设置,相关问题百度或评论。下面调用这个函数时候,我拟定拟定窗口[-160,240]
    img[img < min] = min
    img[img > max] = max
    norm_ = (img - min) / window
    norm_.astype('float32')
    return norm_


root = r'F:\mayo\Mayo_Grand_Challenge-selected (1)\ACR_Phantom_Data\Image_Data\3mm D45\ACR_quarter_3mm_sharp\quarter_3mm_sharp'  # 这是每个病例的路径
savepath = r'C:\Users\18231\Desktop\Image_data_daochu\3mmD45\quarter3mmsharp'  # 之后保存图片的路径

# # 下面遍历每个切片
# i = 0
# for filename in os.listdir(root):
#     img = pydicom.read_file(os.path.join(root, filename))  # .IMA文件
#     img_hu = getCtHU(img)  # 由.IMA文件转换成HU形式的
#     img_np = windowsLevelTransform(Hu=img_hu, window=400, level=40)  # 再由HU形式的转成.numpy形式的
#     cv2.imwrite(savepath + '\%d.png' % i, img_np * 255)  # 注意这里img_np要乘上255即img_np*255,不然保存起来的图片看起来不爽,一片黑
#
i = 0
for filename in os.listdir(root):
    img = pydicom.read_file(os.path.join(root, filename))  # .IMA文件
    img_hu = getCtHU(img)  # 由.IMA文件转换成HU形式的
    img_np = windowsLevelTransform(Hu=img_hu, window=400, level=40)  # 再由HU形式的转成.numpy形式的
    output_filename = os.path.join(savepath, '008-'+f'{i}.png')  # Use f-string to create unique filenames
    cv2.imwrite(output_filename, img_np * 255)
    i += 1  # Increment i for the next iteration
    print(f'{i}.png'+'已生成')
# ...
print('------------已生成完毕---------')
# ...
```话不多说直接上代码,增加了文件个数(任务完成百分比查看)

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值