读取nii数据,转为volume.dat二进制数据

代码

#include
#include
#include"functions.h"
#include
#include


using GrayPixelType = unsigned char;
using OrgPixelType = short;

using OrgImageType = itk::Image<OrgPixelType, 3>;
using OrgImagePointerType = OrgImageType::Pointer;

using GrayImageType = itk::Image<GrayPixelType, 3>;
using GrayImagePointerType = GrayImageType::Pointer;

#define WB(x,nBitCount) (((x)*nBitCount+31)/32*4)
//#define WB(x,nBitCount) ((x)*nBitCount)


void normalizeImageByFilter(
	const OrgImagePointerType& input_image,
	GrayImagePointerType& out_image,
	const double dst_min, const double dst_max)
{
	using rescaleFilterType = itk::RescaleIntensityImageFilter<OrgImageType, GrayImageType>;
	auto rescaleFilter = rescaleFilterType::New();
	rescaleFilter->SetInput(input_image);
	rescaleFilter->SetOutputMinimum(dst_min);
	rescaleFilter->SetOutputMaximum(dst_max);
	try {
		rescaleFilter->Update();
	}
	catch (const itk::ExceptionObject& e) {
		std::cout << e.what() << std::endl;
	}
	out_image = rescaleFilter->GetOutput();
}


int main()
{
	std::string niiPath("./45.nii.gz");

	OrgImagePointerType inputImage;
	readData<OrgImageType, OrgImagePointerType>(niiPath, inputImage);
	OrgImageType::SizeType size = inputImage->GetBufferedRegion().GetSize();
	int w = size[0], h = size[1], d = size[2];
	std::cout << "w = " << w << ", h = " << h << ", d = " << d
		<< std::endl;

	GrayImagePointerType normalizedImage;
	normalizeImageByFilter(inputImage, normalizedImage, 0, 255);

	GrayPixelType* inputImageBuffer = normalizedImage->GetBufferPointer();

	std::string volumePath("./volume.dat");
	FILE* fp = fopen(volumePath.c_str(), "wb");

	fwrite(&w, 1, sizeof(w), fp);
	fwrite(&h, 1, sizeof(h), fp);
	fwrite(&d, 1, sizeof(d), fp);

	int imgSize = w * h;
	GrayPixelType* ptrImageRaw = new GrayPixelType[imgSize];
	memset(ptrImageRaw, 0, imgSize);

	long long wb_new = WB(w, sizeof(GrayPixelType)*8);
	GrayPixelType* ptr_8bits = new GrayPixelType[h * wb_new];
	memset(ptr_8bits, 0, h * wb_new);

	std::cout << sizeof(GrayPixelType) << std::endl;

	try {
		int cnt = 0;
		for (int d_index = 0; d_index < d; ++d_index)
		{
			// 取出第d_index 张切片
			for (int row = 0; row < h; ++row)
			{
				for (int col = 0; col < w; ++col)
				{
					*(ptr_8bits + row * wb_new + col) = inputImageBuffer[cnt];
					cnt += 1;
				}
			}// 取第d_index 张图像结束

			for (int row = 0; row < h; row++)
			{
				memcpy(ptrImageRaw + row * w,
					ptr_8bits + row * wb_new, w*sizeof(GrayPixelType));
			}

			fwrite(ptrImageRaw, w * h, sizeof(GrayPixelType), fp);
		}
		fclose(fp);

		delete[] ptrImageRaw;
		delete[] ptr_8bits;
	}
	catch (...) {
		std::cout << "exception" << std::endl;
	}

	

	return 0;
}

你可能感兴趣的:(c++学习,c++,算法,开发语言)