ITK 实现多张图像转成单个nii.gz或mha文件案例

主要实现的部分是利用NameGeneratorType读入系列图像,见头文件#include "itkNumericSeriesFileNames.h"。

需要包含的头文件有:

#include "itkImage.h"
#include "itkImageSeriesReader.h"
#include "itkImageFileWriter.h"
#include "itkNumericSeriesFileNames.h"
#include "itkPNGImageIO.h"//转成JPG格式,将PNG替换成JPEG就可以。

int main( int argc, char ** argv )
{
 // 需要四个参数,分别是程序起点,第一张图像的编号和最后一张图像的变化,输出文件的名称(包含路径)
 if( argc < 4 )
 {
 std::cerr << "Usage: " << std::endl;
 std::cerr << argv[0] << " firstSliceValue lastSliceValue outputImageFile " << std::endl;
 return EXIT_FAILURE;
 }
//定义读入图像类型,创建对应的reader
 typedef unsigned char  PixelType;
 const unsigned int Dimension = 3;

 typedef itk::Image< PixelType, Dimension > ImageType;

 typedef itk::ImageSeriesReader< ImageType > ReaderType;
 typedef itk::ImageFileWriter< ImageType > WriterType;

 ReaderType::Pointer reader = ReaderType::New();
 WriterType::Pointer writer = WriterType::New();

//输入参数定义
 const unsigned int first = atoi( argv[1] );
 const unsigned int last = atoi( argv[2] );
 const char * outputFilename = argv[3];//输出的文件名加上对应格式的后缀即可,如mha或nii.gz

//系列图像读入
 typedef itk::NumericSeriesFileNames NameGeneratorType;
 NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New();
 nameGenerator->SetSeriesFormat( "vwe%03d.png" );

 nameGenerator->SetStartIndex( first );
 nameGenerator->SetEndIndex( last );
 nameGenerator->SetIncrementIndex( 1 );//张数的增长间距

//读入图像,写出图像,进行Update
 reader->SetImageIO( itk::PNGImageIO::New() );
 reader->SetFileNames( nameGenerator->GetFileNames() );
 writer->SetFileName( outputFilename );
 writer->SetInput( reader->GetOutput() );

 try
 {
 writer->Update();
 }
 catch( itk::ExceptionObject & err )
 {
 std::cerr << "ExceptionObject caught !" << std::endl;
 std::cerr << err << std::endl;
 return EXIT_FAILURE;
 }

 return EXIT_SUCCESS;
}

补充知识:将一组png图片转为nii.gz

主要之前使用matlab 对numpy数组存放方式不是很了解.应该是[z,x,y]这样在itksnamp上看就对了

import SimpleITK as sitk
import glob
import numpy as np
from PIL import Image
import cv2

import matplotlib.pyplot as plt # plt 用于显示图片
def save_array_as_nii_volume(data, filename, reference_name = None):
 """
 save a numpy array as nifty image
 inputs:
 data: a numpy array with shape [Depth, Height, Width]
 filename: the ouput file name
 reference_name: file name of the reference image of which affine and header are used
 outputs: None
 """
 img = sitk.GetImageFromArray(data)
 if(reference_name is not None):
 img_ref = sitk.ReadImage(reference_name)
 img.CopyInformation(img_ref)
 sitk.WriteImage(img, filename)

image_path = './oriCvLab/testCvlab/img/'
image_arr = glob.glob(str(image_path) + str("/*"))
image_arr.sort()

print(image_arr, len(image_arr))
allImg = []
allImg = np.zeros([165, 768,1024], dtype='uint8')
for i in range(len(image_arr)):
 single_image_name = image_arr[i]
 img_as_img = Image.open(single_image_name)
 # img_as_img.show()
 img_as_np = np.asarray(img_as_img)
 allImg[i, :, :] = img_as_np

# np.transpose(allImg,[2,0,1])
save_array_as_nii_volume(allImg, './testImg.nii.gz')
print(np.shape(allImg))
img = allImg[:, :, 55]
# plt.imshow(img, cmap='gray')
# plt.show()

以上这篇ITK 实现多张图像转成单个nii.gz或mha文件案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 使用Nibabel库对nii格式图像的读写操作

    因为后期主要的研究方向是医学图像处理,而现有手头的大部分数据都是nii格式或者是hdr,img格式的数据,所以首先第一步我们需要解决图像的读写问题. 其实使用OpenCV也可以方便的进行图像读取,但是这里暂时只学习Nibabel这个库,后面有时间的话再研究OpenCV在python中的使用. Nibabel的安装 可以通过pip进行安装 pip install nibabel 简单的图像读取和存储操作 import os import nibabel as nib # 读取图像 path='C:

  • 使用SimpleITK读取和保存NIfTI/DICOM文件实例

    我就废话不多说了,大家还是直接看代码吧~ ## using simpleITK to load and save data. import SimpleITK as sitk itk_img = sitk.ReadImage('./nifti.nii.gz') img = sitk.GetArrayFromImage(itk_img) print("img shape:",img.shape) ## save out = sitk.GetImageFromArray(img) # #

  • 读取nii或nii.gz文件中的信息即输出图像操作

    读取nii或者nii.gz文件中的信息,并且输出图像. import matplotlib from matplotlib import pylab as plt import nibabel as nib from nibabel.viewers import OrthoSlicer3D file = '' #你的nii或者nii.gz文件路径 img = nib.load(file) print(img) print(img.header['db_name']) #输出nii的头文件 wid

  • python 读取.nii格式图像实例

    我就废话不多说了,大家还是直接看代码吧~ # encoding=utf8 ''' 查看和显示nii文件 ''' import matplotlib matplotlib.use('TkAgg') from matplotlib import pylab as plt import nibabel as nib from nibabel import nifti1 from nibabel.viewers import OrthoSlicer3D example_filename = '../AD

  • python实现批量nii文件转换为png图像

    之前介绍过单个nii文件转换成png图像: https://www.jb51.net/article/165693.htm 这里介绍将多个nii文件(保存在一个文件夹下)转换成png图像.且图像单个文件夹的名称与nii名字相同. import numpy as np import os #遍历文件夹 import nibabel as nib #nii格式一般都会用到这个包 import imageio #转换成图像 def nii_to_image(niifile): filenames =

  • ITK 实现多张图像转成单个nii.gz或mha文件案例

    主要实现的部分是利用NameGeneratorType读入系列图像,见头文件#include "itkNumericSeriesFileNames.h". 需要包含的头文件有: #include "itkImage.h" #include "itkImageSeriesReader.h" #include "itkImageFileWriter.h" #include "itkNumericSeriesFileNam

  • Caffe图像数据转换成可运行leveldb lmdb文件

    目录 引言 该文件的使用格式 调用linux命令生成图片清单 FLAGS参数组 最后运行脚本文件 引言 在深度学习的实际应用中,我们经常用到的原始数据是图片文件,如jpg,jpeg,png,tif等格式的,而且有可能图片的大小还不一致. 而在caffe中经常使用的数据类型是lmdb或leveldb,因此就产生了这样的一个问题:如何从原始图片文件转换成caffe中能够运行的db(leveldb/lmdb)文件? 在caffe中,作者为我们提供了这样一个文件:convert_imageset.cpp

  • Python OpenCV读取png图像转成jpg图像存储的方法

    如下所示: import os import cv2 import sys import numpy as np path = "F:\\ImageLib\\VRWorks_360_Video _SDK_1.1\\footage14\\" print(path) for filename in os.listdir(path): if os.path.splitext(filename)[1] == '.png': # print(filename) img = cv2.imread(

  • python随机在一张图像上截取任意大小图片的方法

    如下所示: ''' 机器学习中随机产生负样本的 ''' import cv2 import random #读取图片 img=cv2.imread('1.png') #h.w为想要截取的图片大小 h=80 w=80 count=1 while 1:     #随机产生x,y 此为像素内范围产生  y = random.randint(1, 890) x = random.randint(1, 1480) #随机截图  cropImg = img[(y):(y + h), (x):(x + w)]

  • opencv2实现10张图像上下左右拼接融合

    本文实例为大家分享了opencv2实现多张图像上下左右拼接融合的具体代码,供大家参考,具体内容如下 在前面的"opencv2两张图像拼接融合_基于SURF特征提取"博文中,实现了两张左右图像的拼接融合,后来我也实现了多张图像的拼接融合.但是opencv2自带一种函数,直接就实现了图像的上下左右拼接.具体程序如下: #include <iostream> #include<vector> #include <fstream> #include &quo

  • Python Opencv 通过轨迹(跟踪)栏实现更改整张图像的背景颜色

    !!!本博客,是对图像的背景颜色的修改的基础讲解~!!! 还包括一个练习--是对背景色修改的一点应用尝试!!!--始终相信学习多一点探索,脚步会更坚定一些~ 愿所有正在努力的人都可以坚持自己的路一直走下去! 实现轨迹(跟踪)栏功能的函数 函数主要参数讲解 cv.createTrackbar()--创建一个轨迹(跟踪)栏 cv.getTrackbarPos()--获取一个轨迹(跟踪)栏的值 cv.createTrackbar()参数如下: 参数一:trackbarname--轨迹(跟踪)栏名称 参

  • jupyter notebook oepncv 显示一张图像的实现

    感想 我们在用jupyter notebook的时候,经常需要可视化一些东西,尤其是一些图像,我这里给个sample code 环境 opencv-python matplotlib numpy sample import os import numpy as np from matplotlib import pyplot as plt %matplotlib inline img_dir='/Users/eric/Documents/data/wheel_train_val/train/no

  • 详解如何将JAVA程序制作成可以直接执行的exe文件

    突然心血来潮,想自己做个小程序玩玩,但是怎么把他做成一个exe文件,让大家能够更好的理解和使用呢,百度了一下,说是需要exe4j来生成,但是看了很多关于exe4j将java程序生成exe文件的教程,觉着都不是自己想要的结果,还是自己综合一下,写篇文章记录一下. 下载和安装的步骤我就略过了,直接说重点. 一 : 将写好的java程序打成jar包,如下图: 1: . 2: 3: 4: 5:此处填写MANIFEST.MF文件路径,MANIFEST.MF手动创建后放在下项目路径下即可 MANIFEST.

  • 用PyInstaller把Python代码打包成单个独立的exe可执行文件

    之前就想要把自己的BlogsToWordpress打开成exe了.一直没去弄. 又看到有人提到python打开成exe的问题. 所以打算现在就去试试. 注:此处之所有选用BlogsToWordpress,是因为此python脚本够复杂,依赖的模块够多. 如果这个都搞定了,那么其他单个的python文件,和小python项目的打包,就更不成问题了. 1.先去找找,目前主流有哪几种方法. 找到几个名字 cx_Freeze PyInstaller py2exe 2.关于py2exe和PyInstall

  • Ubuntu+python将nii图像保存成png格式

    这里介绍一个nii文件保存为png格式的方法. 这篇文章是介绍多个nii文件保存为png格式的方法: https://www.jb51.net/article/165692.htm 系统:Ubuntu 16.04 软件: python 3.5 先用pip安装nibabel.numpy.imageio.os. import nibabel as nib import numpy as np import imageio import os def read_niifile(niifile): #读

随机推荐