Python dcm转二值图JPG(阈值可调)

#dcm转二值图(阈值可调)
import pydicom
import numpy as np
import os
import cv2
np.set_printoptions(threshold=np.inf)
PathDicom = 'E:\\1thx\\preprocessJPG\\adddcm'  # 存放的dcm文件路径
#OutputFile = "E:\\2_DicomPython\\dicom代码\\DcmtoBinaryjpg\\DcmtoBinary"
#从dcm文件中读出slope和intercept 一般分别为1和-1024 这里直接省略
#dcm = pydicom.read_file(PathDicom+"\\12531097-Thorax^03_Thorax_Rib (Adult)-2022-01-30_0005_0154_752564566.dcm")
#slope = dcm.RescaleSlope    #1
#intercept = dcm.RescaleIntercept  #-1024
slope = 1
intercept = -1024
listFilesDCM = []  # 用lstFilesDCM作为存放DICOM files的列表
FilesDCM = []
#将所有dicom文件读入
for PathName, subdirList, fileList in os.walk(PathDicom):
    for filename in fileList:
        if ".dcm" in filename.lower():  # 判断文件是否为dicom文件
            dcm = pydicom.dcmread(os.path.join(PathName, filename))
            #直接从dcm读出的像素矩阵
            img_arr = dcm.pixel_array
            img_arr.dtype = "int16"
            #print(img_arr)  #打印img_arr

            #CT值的单位是Hounsfield,简称为Hu,范围是-1024-3071。用于衡量人体组织对X射线的吸收率,设定水的吸收率为0Hu。
            #   在DICOM图像读取的过程中,我们会发现图像的像素值有可能不是这个范围,通常是0-4096,这是我们常见到的像素值或者灰度值,这就需要我们在图像像素值(灰度值)转换为CT值。
            #   首先,需要读取两个DICOM Tag信息,(0028|1052):rescale intercept和(0028|1053):rescale slope.
            #   然后通过公式:
            #     Hu = pixel * slope + intercept
            #   计算得到CT值。
            #    利用公式将像素值转为CT值,Hu = pixel * slope + intercept
            for i in range(img_arr.shape[0]):
                for j in range(img_arr.shape[1]):
                    img_arr[i][j] = img_arr[i][j] * slope + intercept
            #print(img_arr)
            #利用阈值转为二值图
            for i in range(img_arr.shape[0]):
                for j in range(img_arr.shape[1]):
                    if img_arr[i][j] >= 662 and img_arr[i][j] <= 1988:     #骨头
                    #if img_arr[i][j] >= -5 and img_arr[i][j] <= 135:  #肌肉组织
                       img_arr[i][j] = 255
                    else:
                        img_arr[i][j] = 0
            #print(img_arr)
            file_name1 = os.path.splitext(filename)[0]  # 只要文件名字,去掉扩展名
            if cv2.imwrite("E:\\1thx\\preprocessJPG\\binary\\" + file_name1 + ".jpg", img_arr):
                print("ok")
                #print(img_arr.shape)
            else:
                print("faulse")
    print("all transformed")

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值