常用自定义函数

6 篇文章 1 订阅
2 篇文章 0 订阅

Json文件读写

  1. 读取json
def read_json(json_file):
    import json
    """
    Read the json file

    :param json_file: read to path
    :return: the dict of json data
    """
    with open(json_file, "rb") as f:
        json_data = json.load(f)
    return json_data
  1. 写入json
def write_json(json_data, json_file):
    import json
    """
    Save the json file

	:param json_data: the dict of json data
    :param json_file: save to path
    :return: 
    """
    with open(json_file, "w") as f:
        json.dump(json_data, f, indent=4, ensure_ascii=False)
    return
  1. 读取yaml
def read_yaml(yaml_file):
    import yaml
    """
    Read the yaml file

    :param yaml_file: read to path
    :return: the dict of yaml data
    """
    with open(yaml_file) as f:
        yaml_data = yaml.safe_load(f.read())
    return yaml_data 

Array插值resize

  1. 一维array
def resize_1d(input, length):
	from scipy.interpolate import interp1d
    """
    Interpolate a 1-D array

    :param input: 1-D array
    :param length: the target length
    :return: the result of interpolate
    """
    x = np.linspace(0, length, input.shape[0])
    f = interp1d(x, input)
    x_new = np.linspace(0, length, length)
    y_new = f(x_new)
    return y_new
  1. N维array
def resize_nd(input, new_size):
    """
    Interpolate a N-D array

    :param input: N-D array
    :param new_size: the target size
    :return: the result of interpolate
    """
    from skimage.transform import resize
    output = resize(input, new_size)
    return output

形态学处理

  1. 膨胀操作
def dilation_nd(input, k=5, iters=1):
    """
    N-D Binary dilation

    :param input: N-D Binary array_like
    :param k: the kernel size
    :param iters: iterations size
    :return: the result of dilation
    """
    from scipy.ndimage import binary_dilation
    nd = len(input.shape)
    kernels = np.ones(k * np.ones(nd).astype(int))
    output = binary_dilation(input, structure=kernels, iterations=iters).astype(int)
    return output
  1. 腐蚀操作
def erosion_nd(input, k=5, iters=1):
    """
    N-D Binary erosion

    :param input: N-D Binary array_like
    :param k: the kernel size
    :param iters: iterations size
    :return: the result of erosion
    """
    from scipy.ndimage import binary_erosion
    nd = len(input.shape)
    kernels = np.ones(k * np.ones(nd).astype(int))
    output = binary_erosion(input, structure=kernels, iterations=iters).astype(int)
    return output
  1. 开操作
def opening_nd(input, k=5, iters=1):
    """
    N-D Binary opening

    :param input: N-D Binary array_like
    :param k: the kernel size
    :param iters: iterations size
    :return: the result of opening
    """
    from scipy.ndimage import binary_opening
    nd = len(input.shape)
    kernels = np.ones(k * np.ones(nd).astype(int))
    output = binary_opening(input, structure=kernels, iterations=iters).astype(int)
    return output
  1. 闭操作
def closing_nd(input, k=5, iters=1):
    """
    N-D Binary closing

    :param input: N-D Binary array_like
    :param k: the kernel size
    :param iters: iterations size
    :return: the result of closing
    """
    from scipy.ndimage import binary_closing
    nd = len(input.shape)
    kernels = np.ones(k * np.ones(nd).astype(int))
    output = binary_closing(input, structure=kernels, iterations=iters).astype(int)
    return output

Pandas读写

  1. Pandas读取excel
def read_excel(file_dir):
    """
    read the path of excel file
    
    :param file_dir: excel file Path
    :return: the values of excel
    """
    import pandas as pd
    data = pd.read_excel(file_dir, header=0)
    return data.values()
  1. Pandas写excel
def save_excel(data, save_dir):
    """
    save data to excel file

    :param data: the list&dict of data
    :param save_dir: the path of save data
    :return:
    """
    import pandas as pd
    dataframe = pd.DataFrame(data)
    dataframe.to_excel(save_dir, sheet_name="data", na_rep="", header=1)
    return

csv和excel的读写类似,excel改成csv就可以了。

  1. Pandas读取pickle
import pandas as pd
# pickle读取pkl文件,会因为操作系统不同出现错误;pandas读取pkl的话,可以避免这个问题
pkl_data = pd.read_pickle(pkl_file)

保存plt上显示的图像

  1. plt显示
def plt_show(input, file):
    """
    show the images

    :param input: the list of 1d&2d array
    :return:
    """
    from matplotlib import pyplot as plt
    num = len(input)
    assert num >= 1
    plt.figure(figsize=(num * 10, 10))
    for i in range(num):
        plt.subplot(1, num, i)
        assert 1 <= len(input[i].shape) <= 2
        if len(input[i].shape) == 1:
            plt.plot(input[i])
        elif len(input[i].shape) == 2:
            plt.imshow(input[i])
            
    f = plt.gcf()
    f.savefig(file.split('.')[0] + ".png")
    f.clear()
    return 

读写nii.gz, mhd图像

这里有一点需要特别注意:SimpleITK读取图像的维度是[z, y, x],而nibabel读取图像的维度是[x, y, z].

  1. SimpleITK读写nii.gz, mhd图像
def itk_read(file):
    """
    read 3D image use SimpleITK

    :param file: the dir of 3D image
    :return: ct_array, 3D array of the image
    :return: info, the image information of origin, direction, space
    """
    import SimpleITK as sitk
    ct = sitk.ReadImage(file)
    ct_array = sitk.GetArrayFromImage(ct)

    origin = ct.GetOrigin()
    direction = ct.GetDirection()
    space = ct.GetSpacing()
    info = [origin, direction, space]
    return ct_array, info


def itk_save(ct_array, info, saved_name):
    """
    save 3D image use SimpleITK

    :param ct_array: 3D array of the image
    :param info: the image information of origin, direction, space
    :param saved_name: the save dir of 3D image
    :return:
    """
    import SimpleITK as sitk
    savedImg = sitk.GetImageFromArray(ct_array)
    [origin, direction, space] = info
    savedImg.SetOrigin(origin)
    savedImg.SetDirection(direction)
    savedImg.SetSpacing(space)
    sitk.WriteImage(savedImg, saved_name)
    return
  1. nibabel读写nii.gz, mhd图像
def nib_read(file):
    """
    read 3D image use nibabel

    :param file: the read dir of 3D image
    :return: ct_array, 3D array of the image
    :return: ct_meta, the image meta information
    """
    import nibabel
    ct = nibabel.load(file)
    ct_array = ct.get_fdata()
    ct_meta = ct.affine
    return ct_array, ct_meta


def nib_save(ct_array, ct_meta, saved_name):
    """
    save 3D image use nibabel

    :param ct_array: 3D array of the image
    :param ct_meta: the image meta information
    :param saved_name: the save dir of 3D image
    :return:
    """
    import nibabel
    new_image = nibabel.Nifti1Image(ct_array, ct_meta)
    nibabel.save(new_image, saved_name)
    return 
  1. VTK读取.vtk文件
def read_vtk(path):
	import vtk
    reader = vtk.vtkPolyDataReader()
    reader.SetFileName(path)
    reader.ReadAllScalarsOn()
    reader.ReadAllVectorsOn()
    reader.ReadAllTensorsOn()
    reader.Update()
    vtkdata = reader.GetOutput()
    num = vtkdata.GetNumberOfPoints()
    x = []
    y = []
    for i in range(num):
        points = vtkdata.GetPoint(i)
        x.append(points[0])
        y.append(points[1])
    x = np.array(x)
    y = np.array(y)
    return x, y
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小吕同学吖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值