今儿刚好用的医学图像处理,看了一些博客,就封装了一下,把三维nii ,转化为 gif,懒得废话了,直接看代码的注释吧:
import cv2
import nibabel as nib
import numpy as np
from PIL import Image
def show_nii_gif(nii_file, save_path="array.gif", show_frame=True):
"""
@Brife:
将 shape=(arr_len, h, w) 的 nii 文件转化为 gif
@Param:
nii_file : nii 文件的路径
show_frame : 是否展示这是第几帧, 默认 True
save_path : 默认为当前路径的 array.gif 文件
"""
img=nib.load(nii_file)
img_arr = img.get_fdata()
img_arr = np.squeeze(img_arr)
img_max, img_min = img_arr.max(), img_arr.min()
img_arr = (img_arr - img_min) / (img_max - img_min) * 255
img_arr = img_arr.astype(np.uint8)
img_RGB_list = [cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) for img in img_arr]
assert 3==len(img_arr.shape)
arr_len, h, w = img_arr.shape
if show_frame:
for i in range(arr_len):
img_RGB_list[i] = cv2.putText(img_RGB_list[i],
'{:>03d}/{:>03d}'.format(i+1, arr_len),
(50, 50),
cv2.FONT_HERSHEY_COMPLEX,
1,
(255, 255, 255),
2)
imgs = [Image.fromarray(img) for img in img_RGB_list]
imgs[0].save(save_path, save_all=True, append_images=imgs[1:], duration=50, loop=0)
show_nii_gif(nii_file='IMG_0002.nii')
展示一哈:
参考了:
Python读取nii文件 https://blog.csdn.net/PKnotnull/article/details/80841410
用openCV在 array 上写字: https://blog.csdn.net/GAN_player/article/details/78155283
灰度图直接转化为三通道灰度图: https://blog.csdn.net/llh_1178/article/details/77833447
Python字符串格式化,"{:>03d}" 死活记不住hhh [向右对齐,并用0补充] https://www.runoob.com/python/att-string-format.html
将ndarray的照片生成git https://stackoverflow.com/questions/63047707/how-do-i-convert-a-numpy-array-to-a-gif
Matplotlib 保存gif (这次没有用上,几年前第一次用,就感觉是个老麻烦的东西,hhh) https://blog.csdn.net/qq_28888837/article/details/85778395
Python skimage 库安装: https://blog.csdn.net/j_starry/article/details/100192206
|