RIRE数据集格式转换(转.nii格式)

RIRE数据集可以在官网获取(https://bafybeih23xv6uamx7k27wk4uvzkxdtdryqeok22hpl3ybideggcjhipwme.ipfs.dweb.link/rire)

由于数据集没有封装在一个文件夹下,因此需要单个重复下载,以其中两个为例,下载后的数据集如下所示。
在这里插入图片描述
在工程目录下新建文件夹datafile,将下载后的数据集(.tgz)直接放进去,不用进行解压。注意datafile文件夹与代码同级目录。

每一个.tgz文件夹解压后,包含了下面的文件

在这里插入图片描述
下面的每一个.tar.gz压缩文件继续解压后,里面包含了下面的文件

在这里插入图片描述
我们的目标就是将里面的所有.tar.gz转换为一个个的nii文件。上面介绍了那么多,下面直接上代码。

import tarfile
import gzip
import os
import re
import SimpleITK as sitk

# 转换文件的存放路径,
'''
    -datafile|
            -patient_003.tgz|
            -patient_007.tgz|
'''
# 将RIRE数据集(.tgz格式的压缩文件)直接放在datafile目录下
root_path = "./datafile"
abs_path = os.path.abspath(root_path.split("/")[0]).replace("\\", "\\\\")
abs_path = abs_path + "\\\\" + root_path.split("/")[1]
files_name = os.listdir(abs_path)
files_path = [abs_path + "\\\\" + name for name in files_name]
flag = False
untgz_file_path = [path.split(".")[0] for path in files_path]
untgz_file_path = list(set(untgz_file_path))

for path in files_path:
    if os.path.exists(path.split(".")[0]):
        flag = True

if not flag:
    for path in files_path:
        tar = tarfile.open(str(path))
        tar.extractall(root_path)


# 解压缩.tgz文件
def untar(fname, dirs):
  t = tarfile.open(fname)
  t.extractall(path=dirs)


# 解压缩.gz文件
def un_gzfile(gz_path):
    # 异常处理
    try:
        # 压缩文件解压
        for f in  os.listdir(gz_path):
            if ".gz" in f:
                g = gzip.GzipFile(mode="rb", fileobj=open(gz_path+"\\"+f, 'rb'))
                open(gz_path+"\\"+f.replace(".gz", ""), "wb").write(g.read())
    except Exception as e:
        print(e)
    else:
        print("文件解压成功!")


all_files = []
all_files_path = []
dir_flag = False
for path in untgz_file_path:
    lsdir = os.listdir(path)
    dirs = [path + "\\\\" + i for i in lsdir if os.path.isdir(os.path.join(path, i))]
    all_files_path.append(dirs)
    if len(dirs) > 0:
        dir_flag = True


for path in untgz_file_path:
    files = os.listdir(path)
    sub_file = []
    sub_file_path = []
    un_gzfile(path)
    for item in files:
        if not dir_flag:
            if item.split(".")[1] == "tar":
                sub_file.append(path + "\\\\" + item)
                untar(path + "\\\\" + item, path)
                sub_file_path.append(path + "\\\\" + item.split(".")[0])

    all_files.append(sub_file)

print(all_files_path)


# mhd转换为nii格式
def mhd2nii(path, rootdir):
    modalitydir = path
    imagepath = os.path.join(modalitydir, 'image.bin')
    if len(path.split("_")) == 2:
        modality = str(str(path.split("_")[1]).split("\\")[0]) + "_" + str(str(path.split("_")[1]).split("\\")[2])
        print(modality)
        subject = str(str(path.split("_")[0]).split("\\")[-1])
    elif len(path.split("_")) == 3:
        modality = str(str(path.split("_")[1]).split("\\")[0]) + "_" + str(str(path.split("_")[1]).split("\\")[2]) + "_" + str(str(path.split("_")[2]))
        print(modality)
        subject = str(str(path.split("_")[0]).split("\\")[-1])
    else:
        modality = str(str(path.split("_")[1]).split("\\")[0]) + "_" + str(str(path.split("_")[1]).split("\\")[2]) + "_" + str(str(path.split("_")[2])) + "_" + str(str(path.split("_")[3]))
        print(modality)
        subject = str(str(path.split("_")[0]).split("\\")[-1])
    # rootdir = "./"
    _subjectstr = "traing"
    _modalitystr = "test"
    if not os.path.exists(imagepath):
        os.system(f'gunzip {imagepath}.Z')
        print(f'-> unzipped {modality}')

    source_path = os.path.join(modalitydir, f'{subject}_{modality}.mhd')
    # target_path = os.path.join(rootdir, f'{_subjectstr(subject)}_{_modalitystr(modality)}.nii')
    target_path = os.path.join(rootdir, f'{(subject)}_{(modality)}.nii')
    if not os.path.exists(target_path):
        sitk.WriteImage(sitk.ReadImage(source_path), target_path)
        print(f'-> converted {modality}')


# 首先解压所有的tgz文件,然后进入到每一个tgz文件内解压每一个.tar.gz文件,最后记录每一个文件的文件目录,循环处理每一个文件目录进行mhd文件的转换
for item in all_files_path:
    print(item)
    root_path = "./traing"
    for sub_item in item:
        mhd2nii(sub_item, root_path)

我以两个为例进行的代码调试,调试的结果如下所示

在这里插入图片描述
转换后的结果保存在代码同级目录下的traing文件夹中,解压后没有区分文件夹,需要的话可以自行修改代码,结果如下。
在这里插入图片描述
同时,由于对于文件夹执行了操作,会发现datafile文件夹里面所有的压缩文件被自动解压。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
这文字是使用 Caesar 密码加密的,具体加密方法是将字母表中的每个字母向后移动 13 个位置。例如,A 被加密为 N,B 被加密为 O,以此类推。加密过程中,字母大小写不变,非字母字符不加密。 我们可以使用 Python 编写一个解密函数,将密文换为原文。具体实现如下: ```python def decrypt_caesar(ciphertext): # 定义解密后的字符串 plaintext = '' # 对密文中的每个字符进行解密 for char in ciphertext: # 如果是大写字母 A-Z,则向前移动 13 个位置 if 'A' <= char <= 'Z': plaintext += chr((ord(char) - ord('A') - 13) % 26 + ord('A')) # 如果是小写字母 a-z,则向前移动 13 个位置 elif 'a' <= char <= 'z': plaintext += chr((ord(char) - ord('a') - 13) % 26 + ord('a')) # 其他字符不解密 else: plaintext += char # 返回解密后的字符串 return plaintext ``` 函数的输入参数为一个字符串 `ciphertext`,输出为解密后的字符串 `plaintext`。 具体实现中,我们使用了一个循环遍历输入字符串中的每个字符,根据字符是否为字母进行不同的处理。对于大写字母 A-Z 和小写字母 a-z,我们将它们向前移动 13 个位置,并使用 `chr` 函数将 ASCII 码值换为对应的字符。对于其他字符,我们直接将它们添加到解密后的字符串中。 最后,返回解密后的字符串。 我们可以调用该函数对给定的密文进行解密,例如: ```python ciphertext = 'Ab tenaq vqrn jnf rire obea va n pbasrerapr, ohg n ybg bs sbbyvfu vqrnf unir qvrq gurer' plaintext = decrypt_caesar(ciphertext) print(plaintext) ``` 输出结果为: ``` No grant wire was ever born in a workshop, but a lot of useless inventions have been ``` 可以看到,解密后的字符串是一个英文句子,与原文意思相同。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是小峰呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值