template <typename T>
static bool WriteMhd(const std::string& strFileName, const T* pData, const unsigned int* uiImgSize, const double* dImgSpacing, const std::string& strType)
{
std::string sFileName = strFileName;
if (4 < sFileName.size())
{
std::string sExt = sFileName.substr(sFileName.size() - 4, 4);
boost::to_lower(sExt);
if (".mhd" == sExt)
{
sFileName = sFileName.substr(0, sFileName.size() - 4);
}
}
TransInfo2MHD(sFileName + ".info", uiImgSize, dImgSpacing, strType);
WriteRawImgData(sFileName + ".raw", pData, uiImgSize[0] * uiImgSize[1] * uiImgSize[2]);
return true;
}
static bool TransInfo2MHD(const std::string& strFileName, const unsigned uiSize[3], const double dSpacing[3], const std::string& strType)
{
int ifind1 = static_cast<int>(strFileName.rfind("\\"));
int ifind2 = static_cast<int>(strFileName.rfind("/"));
int iIndex = ifind1;
if (ifind1 > ifind2 && 0 <= ifind1)
{
iIndex = ifind1;
}
else if (ifind2 > ifind1 && 0 <= ifind2)
{
iIndex = ifind2;
}
std::string strImageName = strFileName.substr(iIndex + 1, strFileName.rfind(".") - iIndex - 1);
std::string strOutFileName = strFileName.substr(0, strFileName.rfind(".")) + ".mhd";
std::fstream fileStream;
fileStream.open(strOutFileName, std::ios::out);
if (!fileStream.is_open())
{
std::cerr << "Note: Open writing " + strFileName + " file failed!" << std::endl;
return false;
}
fileStream << "ObjectType = Image" << std::endl;
fileStream << "NDims = 3" << std::endl;
fileStream << "BinaryData = True" << std::endl;
fileStream << "BinaryDataByteOrderMSB = False" << std::endl;
fileStream << "CompressedData = False" << std::endl;
fileStream << "TransformMatrix = 1 0 0 0 1 0 0 0 1" << std::endl;
fileStream << "Offset = 0 0 0" << std::endl;
fileStream << "CenterOfRotation = 0 0 0" << std::endl;
fileStream << "AnatomicalOrientation = RAI" << std::endl;
fileStream << "ElementSpacing = " << dSpacing[0] << " " << dSpacing[1] << " " << dSpacing[2] << std::endl;
fileStream << "DimSize = " << uiSize[0] << " " << uiSize[1] << " " << uiSize[2] << std::endl;
fileStream << "ElementType = MET_" << strType << std::endl;
fileStream << "ElementDataFile = " << strImageName << ".raw" << std::endl;
fileStream.close();
return true;
}
template <typename T>
static bool WriteRawImgData(const std::string& strFileName, const T* pData, unsigned int uiLength)
{
std::fstream fileStream;
fileStream.open(strFileName, std::ios::out | std::ios::binary);
if (!fileStream.is_open())
{
std::cerr << "Note: Open " + strFileName + " file failed!" << std::endl;
return false;
}
fileStream.write((char*)pData, sizeof(T) * uiLength);
fileStream.close();
return true;
}
写一个模板函数,医学影像用于导出mask
最新推荐文章于 2024-11-09 13:08:09 发布
这段代码定义了三个静态函数,用于处理MHD图像文件的写入。WriteMhd函数接收图像数据、尺寸、间隔和类型信息,然后调用其他两个函数将数据写入.info和.raw文件。TransInfo2MHD函数生成.MHD头文件,包含图像元数据。WriteRawImgData则负责写入二进制图像数据。
摘要由CSDN通过智能技术生成