Пример #1
0
void
LocalService::SolveFile( 
  const boost::filesystem::path & fileName, const boost::filesystem::path & path,
  ResultSet &result)
{
  OFString ofStr;

  DcmFileFormat dfile;
  OFCondition cond = dfile.loadFile( fileName.string().data());
  if (! cond.good())
  {
    LOG( "Loading of " << fileName << " failed. ("  << cond.text() << ")" );
    return;
  }

  DcmDataset *dataSet = dfile.getDataset();

  TableRow row;
  SerieInfo serInfo;

  // load data and check if it is already in tree
  CheckDataSet( dataSet, serInfo, row, path.string());

  // look if this row is already in resultSet
  FoundStudiesSet::iterator found = m_alreadyFoundInRun.find(row.studyID);
  // if not, add it
  if( found == m_alreadyFoundInRun.end() )
  {
    m_alreadyFoundInRun.insert( FoundStudiesSet::value_type( row.studyID) );
    result.push_back( row);
  }
}
Пример #2
0
bool
ParserDicom::isValidFile(string filename)
{
    DcmFileFormat dcm;
    OFCondition cond = dcm.loadFile(filename.c_str());
    return cond.good();
}
Пример #3
0
void DicomImporter::DetermineSopClass(const String& _file)
{
	try
	{
		DcmFileFormat ff;
		ff.loadFile(_file.c_str());
		DcmMetaInfo *m = ff.getMetaInfo();
		
		DcmElement* elem = NULL;
		elem = DcmtkHelper::searchElement(m, 0002, 0002);

		std::string sopClass;
		if (elem != NULL)
		{
			sopClass = DcmtkConvert::DcmElementValueToString(elem);
		}
		else
		{
			return;
		}

		if (sopClass == "1.2.840.10008.1.3.10")
		{
			dicomdirFiles.push_back(_file);
		}
		else
		{
			nonDicomdirFiles.push_back(_file);
		}
	}
	catch (...)
	{
		throw;
	}
}
Пример #4
0
//------------------------------------------------------------------------------
void ctkDICOMDatabase::loadFileHeader (QString fileName)
{
  Q_D(ctkDICOMDatabase);
  DcmFileFormat fileFormat;
  OFCondition status = fileFormat.loadFile(fileName.toLatin1().data());
  if (status.good())
    {
    DcmDataset *dataset = fileFormat.getDataset();
    DcmStack stack;
    while (dataset->nextObject(stack, true) == EC_Normal)
      {
      DcmObject *dO = stack.top();
      if (dO->isaString())
        {
        QString tag = QString("%1,%2").arg(
            dO->getGTag(),4,16,QLatin1Char('0')).arg(
            dO->getETag(),4,16,QLatin1Char('0'));
        std::ostringstream s;
        dO->print(s);
        d->LoadedHeader[tag] = QString(s.str().c_str());
        }
      }
    }
  return;
}
Пример #5
0
bool DCMTKImageIO::CanReadFile(const char* filename)
{
    DcmFileFormat dicomFile;
    OFCondition condition = dicomFile.loadFile( filename );
    if ( !condition.good() ) {
        return false;
    }

    E_TransferSyntax xfer = dicomFile.getDataset()->getOriginalXfer();

    if( xfer == EXS_JPEG2000LosslessOnly ||
        xfer == EXS_JPEG2000 ||
        xfer == EXS_JPEG2000MulticomponentLosslessOnly ||
        xfer == EXS_JPEG2000Multicomponent ) {
        return false;
    }

    // search for mandatory tags
    DcmStack stack;
    DcmTagKey searchKey;
    unsigned int group = 0x0028; // samples per pixel
    unsigned int elem  = 0x0002; // samples per pixel

    searchKey.set(group, elem);
    if (dicomFile.search(searchKey, stack, ESM_fromHere, OFTrue) != EC_Normal)
        return false;

    group = 0x0028; // pixel type
    elem  = 0x0100; // pixel type
    searchKey.set(group, elem);
    if (dicomFile.search(searchKey, stack, ESM_fromHere, OFTrue) != EC_Normal)
        return false;

    return true;
}
Пример #6
0
// Load our vtkImageData object from a list of DICOM image filenames...
// http://www.vtk.org/pipermail/vtkusers/2007-August/042635.html
void vtkDicom::load_dcmFiles(QStringList dcm_fileList) {
    DcmFileFormat dcm;
    std::string imgFname;
    std::cout << "vtkdicom: Files/Images(?): " << dcm_fileList.size() << "\n";
    for (int sei = 0; sei < dcm_fileList.size(); ++sei) {
        imgFname = dcm_fileList.at(sei).toLocal8Bit().constData();
        OFCondition status = dcm.loadFile(imgFname.c_str());
        if (!status.good()) {
            std::cout << "    vtkdicom: Error: cannot read file (" << status.text() << ")" << "\n";
            return;
        }
        if (sei == 0) {
            OFString acquisitionNumber, instanceNumber, imagePositionPatient, patientsName;
            DcmDataset *dcmDs = dcm.getDataset();
            dcmDs->findAndGetOFStringArray(DCM_ImagePositionPatient, imagePositionPatient);
            dcmDs->findAndGetOFString(DCM_AcquisitionNumber, acquisitionNumber);
            dcmDs->findAndGetOFString(DCM_InstanceNumber, instanceNumber);
            dcmDs->findAndGetOFString(DCM_PatientName, patientsName);
            std::cout << "vtkdicom: I#, IPP: " << instanceNumber << " - " << imagePositionPatient << "\n";
        }
        dcm.loadAllDataIntoMemory();
        const unsigned short* p = NULL;
        dcm.getDataset()->findAndGetUint16Array(DCM_PixelData, p);

    }
}
Пример #7
0
bool DicomImporter::IsFileValid(const String& _file)
{
	try
	{
		//
		// create the dicom fileformat and check if this is possible
		//
		DcmFileFormat ff;
		OFCondition cond = ff.loadFile(_file.c_str());
		if (cond.bad()) return false;
	    
		//
		// ist it in part 10 format (does meta-header exist)?
		//
		DcmMetaInfo *m = ff.getMetaInfo();
		if (m == NULL || m->card() == 0) return false;

		//
		// does the file contain data (does the dataset exist)?
		//
		DcmDataset *d = ff.getDataset();
		if (d == NULL) return false;

		//
		// yes, it is a valid dicom file!
		//
		return true;
	}
	catch (...)
	{
		throw;
	}
}
Пример #8
0
Examen*
ParserDicom::loadFile(string dirName)
{
    // Open directory
    DIR* dir = opendir(dirName.c_str());
    if (dir == NULL) {
        return NULL;
    }

    // Get examen informations
    ExamenParams* params = getInfos(dir, dirName);
    if (params == NULL) {
        return NULL;
    }

    // Create struct examen
    Volume* img = new Volume(params->width, params->height, params->depth);
    Examen* exam = new Examen(img, params);

    // Read data
    int index = 0;
    struct dirent* file;
    rewinddir(dir);
    string pathDirectory = dirName + PATH_SEPARATOR;
    int tabSize = params->width * params->height;
    float tab[tabSize];
    while ((file = readdir(dir)) != NULL) {
        if (strcmp(file->d_name, ".") != 0 &&
                strcmp(file->d_name, "..") != 0) {
            string fullpath = pathDirectory + file->d_name;
            DcmFileFormat dcm;
            OFCondition cond = dcm.loadFile(fullpath.c_str());
            if (cond.bad()) {
                delete img;
                delete params;
                return NULL;
            }
            DiDocument* didoc = new DiDocument(fullpath.c_str());
            DiMono2Image* dimg = new DiMono2Image(didoc, EIS_Normal);
            OFString s;
            dcm.getDataset()->findAndGetOFString(DCM_BitsStored, s);
            int bitsStored = atoi(s.c_str());

            short* slice = (short*) dimg->getOutputData(0, bitsStored, 0);
            for(int i=0; i<tabSize; ++i) {
                tab[i] = (float) slice[i];
            }
            img->setSlice(tab, index++);
            delete dimg;
            delete didoc;
        }
    }
    closedir(dir);
    return exam;
}
  mitk::DataNode::Pointer RTDoseReader::
      LoadRTDose(const char* filename)
  {
    DcmFileFormat fileformat;
    OFCondition outp = fileformat.loadFile(filename, EXS_Unknown);
    if(outp.bad())
    {
      MITK_ERROR << "Cant read the file" << std::endl;
    }
    DcmDataset *dataset = fileformat.getDataset();

    std::string name = filename;
    itk::FilenamesContainer file;
    file.push_back(name);

    mitk::DicomSeriesReader* reader = new mitk::DicomSeriesReader;

    mitk::DataNode::Pointer originalNode = reader->LoadDicomSeries(file,false);

    if(originalNode.IsNull())
    {
      MITK_ERROR << "Error reading the dcm file" << std::endl;
      return 0;
    }

    mitk::Image::Pointer originalImage
        = dynamic_cast<mitk::Image*>(originalNode->GetData());

    DRTDoseIOD doseObject;
    OFCondition result = doseObject.read(*dataset);

    if(result.bad())
    {
      MITK_ERROR << "Error reading the Dataset" << std::endl;
      return 0;
    }

    OFString gridScaling;
    Float32 gridscale;

    doseObject.getDoseGridScaling(gridScaling);
    gridscale = OFStandard::atof(gridScaling.c_str());

    AccessByItk_1(originalImage, MultiplayGridScaling, gridscale);

    double prescripeDose = this->GetMaxDoseValue(dataset);

    originalNode->SetName("RT Dose");
    originalNode->SetFloatProperty(mitk::Constants::PRESCRIBED_DOSE_PROPERTY_NAME.c_str(),prescripeDose);
    originalNode->SetFloatProperty(mitk::Constants::REFERENCE_DOSE_PROPERTY_NAME.c_str(), 40);
    originalNode->SetBoolProperty(mitk::Constants::DOSE_PROPERTY_NAME.c_str(),true);
    return originalNode;
  }
Status ConvertDicomToLittleEndian::convert(QString inputFile, QString outputFile)
{
    DcmFileFormat fileformat;
    DcmDataset *dataset = fileformat.getDataset();
    OFCondition error;
    Status state;
    // Transfer Syntax del fitxer d'entrada
    E_TransferSyntax opt_ixfer = EXS_Unknown;
    E_FileReadMode opt_readMode = ERM_autoDetect;
    E_TransferSyntax opt_oxfer = EXS_LittleEndianExplicit;
    QString descriptionError;
    E_EncodingType opt_oenctype = EET_ExplicitLength;
    E_GrpLenEncoding opt_oglenc = EGL_recalcGL;
    E_PaddingEncoding opt_opadenc = EPD_noChange;
    OFCmdUnsignedInt opt_filepad = 0;
    OFCmdUnsignedInt opt_itempad = 0;
    E_FileWriteMode writeMode = EWM_fileformat;

    error = fileformat.loadFile(qPrintable(QDir::toNativeSeparators(inputFile)), opt_ixfer, EGL_noChange, DCM_MaxReadLength, opt_readMode);

    if (error.bad())
    {
        ERROR_LOG(QString("No s'ha pogut obrir el fitxer a convertir LittleEndian %1, descripcio error: %2").arg(inputFile, error.text()));
        return state.setStatus(error);
    }
    dataset->loadAllDataIntoMemory();

    DcmXfer opt_oxferSyn(opt_oxfer);

    dataset->chooseRepresentation(opt_oxfer, NULL);

    if (!dataset->canWriteXfer(opt_oxfer))
    {
        descriptionError = "Error: no conversion to transfer syntax " + QString(opt_oxferSyn.getXferName()) + " possible";
        state.setStatus(qPrintable(descriptionError), false, 1300);
        ERROR_LOG(descriptionError);
        return state;
    }

    error = fileformat.saveFile(qPrintable(QDir::toNativeSeparators(outputFile)), opt_oxfer, opt_oenctype, opt_oglenc, opt_opadenc,
                                OFstatic_cast(Uint32, opt_filepad), OFstatic_cast(Uint32, opt_itempad), writeMode);

    if (!error.good())
    {
        ERROR_LOG(QString("S'ha produit un error al intentar gravar la imatge %1 convertida a LittleEndian al path %2, descripcio error: %3")
                     .arg(inputFile, outputFile, error.text()));
    }

    return state.setStatus(error);
}
Пример #11
0
int main(void)
{
	DcmFileFormat fileformat;
	OFCondition oc = fileformat.loadFile("D:\\021A3C1C.dcm");
	if(oc.good())
	{
		OFString patientName;
		if(fileformat.getDataset()->findAndGetOFString(DCM_PatientName, patientName).good())
		{
			std::cout<<"Patient Name:"<<patientName<<std::endl;
		}
	}
	return 0;
}
Пример #12
0
int Opendcm::loadDcmFile()
{

        // OFCondition status;
        DcmFileFormat fileformat;
        fileformat.loadFile("/home/jeannypan/Documents/dcmtk_image/real_dicom.dcm");
        QString sopClass,;
        fileformat.getMetaInfo()->findAndGetString(DCM_MediaStorageSOPClassUID),sopClass





//        QString out;
//        string sopClass;
//        status= fileformat.loadFile("/home/jeannypan/Documents/dcmtk_image/real_dicom.dcm");
//        if (status.good())
//        {
//                OFString sopClassUID, xferUID;
//                //if(fileformat.getMetaInfo()->findAndGetString(DCM_MediaStorageSOPClassUID),sopClassUID).good())
//                if(fileformat.getMetaInfo()->findAndGetOFString(DCM_MediaStorageSOPClassUID,sopClassUID).good())

//                    //COUT << "SOP Class UID:" << sopClassUID << OFendl;
//                    sopClass =sopClassUID;
//                    sopClass = QString ::fromStdString(sopClass);
//                    //sopClass = QsopClassUID;
//                    //out="SOP Class UID:";
//                    //out += sopClass;

//                    ui->textEdit->setPlainText(sopClass);

//                //ui->textBrowser->out();

//                if(fileformat.getMetaInfo() ->findAndGetOFString(DCM_TransferSyntaxUID,xferUID).good())
//                    //COUT << "Transfer Syntax UID:" << xferUID << OFendl;
//                    out="SOP Class UID:";//+sopClassUID;
//                    ui->textEdit->setText(out);
//                //ui->textBrowser->out();
//                //fileformat.print(out);

//        } else
//        //cerr << "Error: cannot read DICOM file"<<status.text()<<endl;
//            out="Error: cannot read DICOM file";//+sopClassUID;
//            ui->textEdit->setPlainText(out);
//        //ui->textBrowser->out();


               return 0;

}
Пример #13
0
std::string ImageMatrix::get_patientname(const std::string & dirpath){
	std::string filepath = dirpath + "\\ADC\\ADC_1";
	DcmFileFormat *pDicomFile = new DcmFileFormat();
	OFCondition oc = pDicomFile->loadFile(filepath.c_str());
	if(oc.good()){
		DcmDataset *pDataset = pDicomFile->getDataset();
		const char * name;
		pDataset -> findAndGetString(DCM_PatientName, name);
		std::string res(name);
		delete pDataset;
		return res;
	}
	else
	return "f**k";
}
Пример #14
0
void vtkDicom::dumpDicomFile(std::string imgFname)
{
    DcmFileFormat dfile;
    OFCondition status = dfile.loadFile(imgFname.c_str());
    if (status.good()) {
        OFString acquisitionNumber, instanceNumber, imagePositionPatient, patientsName;
        dfile.loadAllDataIntoMemory();
        DcmDataset *dcmDs = dfile.getDataset();
        dcmDs->findAndGetOFStringArray(DCM_ImagePositionPatient, imagePositionPatient);
        dcmDs->findAndGetOFString(DCM_AcquisitionNumber, acquisitionNumber);
        dcmDs->findAndGetOFString(DCM_InstanceNumber, instanceNumber);
        dcmDs->findAndGetOFString(DCM_PatientName, patientsName);
        std::cout << "    " << instanceNumber << " - " << imagePositionPatient << "\n";
    } else {
        std::cout << "    Error: cannot read file (" << status.text() << ")" << "\n";
    }
}
Пример #15
0
void
LocalService::SolveFileGET( const boost::filesystem::path & fileName,
  const std::string &patientID,
	const std::string &studyID,
	const std::string &serieID,
  DicomObjSet &result,
  const std::string &path)
{
  OFString ofStr;

  DcmFileFormat dfile;
  OFCondition cond = dfile.loadFile( fileName.string().data());
  if (! cond.good())
  {
    LOG( "Loading of " << fileName << " failed. ("  << cond.text() << ")" );
    return;
  }

  DcmDataset *dataSet = dfile.getDataset();

  TableRow row;
  SerieInfo serInfo;

  // load data and check if it is already in tree
  CheckDataSet( dataSet, serInfo, row, path);

  // compare with wantend ones
  if( row.patientID == patientID
    && row.studyID == studyID
    && serInfo.id == serieID)
  {
    // if it mathes, insert new image into result
    DicomObj buddy;
    result.push_back( buddy);

    // copy dataset reference & init
    DicomObj *newOne = &result.back();
    newOne->Load( fileName.string() );
    newOne->Init();
  }
}
Пример #16
0
void ctkDICOMDataset::InitializeFromFile(const QString& filename,
                                         const E_TransferSyntax readXfer,
                                         const E_GrpLenEncoding groupLength,
                                         const Uint32 maxReadLength,
                                         const E_FileReadMode readMode)
{
  DcmDataset *dataset;

  DcmFileFormat fileformat;
  OFCondition status = fileformat.loadFile(filename.toAscii().data(), readXfer, groupLength, maxReadLength, readMode);
  dataset = fileformat.getAndRemoveDataset();

  if (!status.good())
  {
    qDebug() << "Could not load " << filename << "\nDCMTK says: " << status.text();
    delete dataset;
    return;
  }

  InitializeFromDataset(dataset, true);
}
Пример #17
0
bool DicomImageLoader::supportsFileType( const string &url ) {
  // DicomImageLoader try to load some DDS image, then it hangs, so stop
  // using DicomImageLoader to load it when DDSImageLoader can do it
  if( DDSImageLoader::supportsFileType(url) ) {
    return false;
  }
  // set the dcmtk console to write to the H3D console
  ofConsole.setCerr( &H3DUtil::Console );
  ofConsole.setCout( &H3DUtil::Console );

  // temporarily shut down console to avoid warning messages from
  // dcmtk while checking if supported.
  H3DUtil::Console.disable();

  DcmFileFormat fileformat;
  OFCondition status = fileformat.loadFile( url.c_str(), EXS_Unknown, 
                                            EGL_noChange, 0 );

  // restore console output level.
  H3DUtil::Console.enable();
  
  return status.good();
}
  IFileIO::ConfidenceLevel DICOMSegmentationIO::GetReaderConfidenceLevel() const
  {
    if (AbstractFileIO::GetReaderConfidenceLevel() == Unsupported)
      return Unsupported;

    const std::string fileName = this->GetLocalFileName();

    DcmFileFormat dcmFileFormat;
    OFCondition status = dcmFileFormat.loadFile(fileName.c_str());

    if (status.bad())
      return Unsupported;

    OFString modality;
    if (dcmFileFormat.getDataset()->findAndGetOFString(DCM_Modality, modality).good())
    {
      if (modality.compare("SEG") == 0)
        return Supported;
      else
        return Unsupported;
    }
    return Unsupported;
  }
Пример #19
0
ExamenParams*
ParserDicom::getInfos(DIR* dir, string dirName)
{
    struct dirent* file = getOneFile(dir);
    if (file == NULL) {
        return NULL;
    }
    string fullpath = dirName + PATH_SEPARATOR + file->d_name;
    DcmFileFormat dcm;
    OFCondition cond = dcm.loadFile(fullpath.c_str());
    if (cond.bad()) {
        return NULL;
    }

    Information* generalInfos = new Information();
    OFString s;
    dcm.getDataset()->findAndGetOFString(DCM_PatientName, s);
    generalInfos->addInformation("Patient name", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_PatientID, s);
    generalInfos->addInformation("Patient ID", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_PatientBirthDate, s);
    generalInfos->addInformation("Patient birthday", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_PatientAge, s);
    generalInfos->addInformation("Patient age", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_PatientSex, s);
    generalInfos->addInformation("Patient sex", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_PatientSize, s);
    generalInfos->addInformation("Patient size", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_PatientWeight, s);
    generalInfos->addInformation("Patient weight", s.c_str());

    dcm.getDataset()->findAndGetOFString(DCM_ImagePositionPatient, s);
    generalInfos->addInformation("Image position patient", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_ImageOrientationPatient, s);
    generalInfos->addInformation("Image orientation patient", s.c_str());

    dcm.getDataset()->findAndGetOFString(DCM_StudyID, s);
    generalInfos->addInformation("Study data", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_StudyDate, s);
    generalInfos->addInformation("Study date", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_StudyTime, s);
    generalInfos->addInformation("Study time", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_StudyDescription, s);
    generalInfos->addInformation("Study description", s.c_str());

    dcm.getDataset()->findAndGetOFString(DCM_BitsAllocated, s);
    generalInfos->addInformation("Bits allocated", s.c_str());

    dcm.getDataset()->findAndGetOFString(DCM_BitsStored, s);
    generalInfos->addInformation("Bits stored", s.c_str());

    dcm.getDataset()->findAndGetOFString(DCM_HighBit, s);
    generalInfos->addInformation("High bit", s.c_str());

    generalInfos->addInformation("Intercept", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_RescaleIntercept, s);
    int intercept = atoi(s.c_str());
    generalInfos->addInformation("Slope", s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_RescaleSlope, s);

    int slope = atoi(s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_WindowCenter, s);
    generalInfos->addInformation("Window center", s.c_str());
    int Wcenter=atoi(s.c_str());
    dcm.getDataset()->findAndGetOFString(DCM_WindowWidth, s);
    generalInfos->addInformation("Window width", s.c_str());
    int Wwidth=atoi(s.c_str());

    dcm.getDataset()->findAndGetOFString(DCM_SliceThickness, s);
    generalInfos->addInformation("Slice thickness", s.c_str());
    float Sthickness = atof(s.c_str());

    dcm.getDataset()->findAndGetOFString(DCM_WindowCenterWidthExplanation, s);
    generalInfos->addInformation("WindowCenterWidthExplanation", s.c_str());

    dcm.getDataset()->findAndGetOFString(DCM_Manufacturer, s);
    generalInfos->addInformation("Manufacturer", s.c_str());

    //---------------------------------------------
    // Affectation des parametres de l'examen
    //---------------------------------------------
    GrayTranslationFunction gtf(slope, intercept);
    ExamenParams* params = new ExamenParams(gtf, fullpath, generalInfos);

    params->getGrayViewWindow().setLuminosity(Wcenter);
    params->getGrayViewWindow().setContrast(Wwidth);
    //params->getGrayViewWindow().setMin(HundsfieldValue::min()); // Must choose !
    //params->getGrayViewWindow().setMax(HundsfieldValue::max());
    //params->setParametersSI(Sthickness);

    //---------------------------------------------
    // Examen size informations
    //---------------------------------------------
    DiDocument* didoc = new DiDocument(fullpath.c_str());
    DiMono2Image* dimg = new DiMono2Image(didoc, EIS_Normal);

    params->width = dimg->getColumns();
    params->height = dimg->getRows();
    params->depth = nbFiles(dir);

    params->resolutionX = dimg->getPixelWidth();;
    params->resolutionY = dimg->getPixelHeight();;
    params->resolutionZ = Sthickness; // check

    ostringstream sNbSlice, sSize, sResX, sResY;
    sResX << params->resolutionX;
    sResY << params->resolutionY;
    sNbSlice << params->depth + 1;
    sSize << params->width << " " << params->height;

    generalInfos->addInformation("Slice number", sNbSlice.str());
    generalInfos->addInformation("Scan resolution (x, y)", sSize.str());
    generalInfos->addInformation("Pixel resolution X", sResX.str());
    generalInfos->addInformation("Pixel resolution Y", sResY.str());

    delete dimg;
    delete didoc;

    return params;
}
Пример #20
0
//************************************
// Method:    Open
// FullName:  CDcmMerger::Open
// Access:    public 
// Returns:   int
// Qualifier:
// Parameter: CStringList * in_pFileList
// Purpose:   
//************************************
int CDcmMerger::Open(CStringList* in_pFileList)
{
	int retcode = SV_NORMAL;

	for (INT i = 0; i< in_pFileList->GetCount(); i++)
	{
		POSITION pos = NULL;
		pos = in_pFileList->FindIndex(i);
		if(pos != NULL)
		{
			CString sFileName = in_pFileList->GetAt(pos);
			char* pzTempName;

			//Convert to ANSI code
			if(CUtility::UnicodeToAnsi(sFileName,&pzTempName) != ERROR_SUCCESS) 
				retcode = SV_SYSTEM_ERR;

			//Create DICOM file access object
			DcmFileFormat* pDcmFile = NULL;
			DicomImage* pDcmImage = NULL;

			//*********Create file object 
			pDcmFile = new DcmFileFormat();					
			if (pDcmFile == NULL) retcode = SV_MEMORY_ERR;
			//Load file
			E_TransferSyntax xfer;
			if(retcode == SV_NORMAL)
			{
				OFCondition cond = pDcmFile->loadFile(pzTempName, 
													  EXS_Unknown, 
													  EGL_withoutGL, 
													  DCM_MaxReadLength,
													  ERM_autoDetect);
				if (cond.bad()) retcode = SV_FILEIO_ERROR;
				else xfer = pDcmFile->getDataset()->getOriginalXfer();				
			}

			OFCmdUnsignedInt    opt_frame = 0;                    //default: start from first frame
			OFCmdUnsignedInt    opt_frameCount = 0;               //default: process all frame

			if(retcode == SV_NORMAL)
			{
				//*********Create image object
				pDcmImage = new DicomImage(pDcmFile, xfer, CIF_AcrNemaCompatibility, opt_frame, opt_frameCount);

				if (pDcmImage == NULL) 
					retcode = SV_MEMORY_ERR;
				else if (pDcmImage->getStatus() != EIS_Normal)
					retcode = SV_UNSUPPORT_FORMAT;			

			}

			if(retcode == SV_NORMAL)
			{
				// VOI LUT processing [1/31/2009 QUYPS]
				pDcmImage->setMinMaxWindow();

				//Add to list
				m_FileList.AddTail(pDcmFile);
				m_ImageList.AddTail(pDcmImage);
			}
			else
			{
				delete pDcmFile;
				delete pDcmImage;
			}
			//Release memory
			delete[] pzTempName;			
		}
		else
		{
			retcode = SV_SYSTEM_ERR;
		}

		//if error occur, escape from loop
		if (retcode != SV_NORMAL) break;		
	}
	return retcode;
}
  std::vector<BaseData::Pointer> DICOMSegmentationIO::Read()
  {
    mitk::LocaleSwitch localeSwitch("C");

    LabelSetImage::Pointer labelSetImage;
    std::vector<BaseData::Pointer> result;

    const std::string path = this->GetLocalFileName();

    MITK_INFO << "loading " << path << std::endl;

    if (path.empty())
      mitkThrow() << "Empty filename in mitk::ItkImageIO ";

    try
    {
      // Get the dcm data set from file path
      DcmFileFormat dcmFileFormat;
      OFCondition status = dcmFileFormat.loadFile(path.c_str());
      if (status.bad())
        mitkThrow() << "Can't read the input file!";

      DcmDataset *dataSet = dcmFileFormat.getDataset();
      if (dataSet == nullptr)
        mitkThrow() << "Can't read data from input file!";

      // Read the DICOM SEG images (segItkImages) and DICOM tags (metaInfo)
      dcmqi::ImageSEGConverter *converter = new dcmqi::ImageSEGConverter();
      pair<map<unsigned, ImageType::Pointer>, string> dcmqiOutput = converter->dcmSegmentation2itkimage(dataSet);

      map<unsigned, ImageType::Pointer> segItkImages = dcmqiOutput.first;

      // For each itk image add a layer to the LabelSetImage output
      for (auto &element : segItkImages)
      {
        // Get the labeled image and cast it to mitkImage
        typedef itk::CastImageFilter<itkInternalImageType, itkInputImageType> castItkImageFilterType;
        castItkImageFilterType::Pointer castFilter = castItkImageFilterType::New();
        castFilter->SetInput(element.second);
        castFilter->Update();

        Image::Pointer layerImage;
        CastToMitkImage(castFilter->GetOutput(), layerImage);

        // Get pixel value of the label
        itkInternalImageType::ValueType segValue = 1;
        typedef itk::ImageRegionIterator<const itkInternalImageType> IteratorType;
        // Iterate over the image to find the pixel value of the label
        IteratorType iter(element.second, element.second->GetLargestPossibleRegion());
        iter.GoToBegin();
        while (!iter.IsAtEnd())
        {
          itkInputImageType::PixelType value = iter.Get();
          if (value != 0)
          {
            segValue = value;
            break;
          }
          ++iter;
        }

        dcmqi::JSONSegmentationMetaInformationHandler metaInfo(dcmqiOutput.second.c_str());
        metaInfo.read();
        MITK_INFO << "Input " << metaInfo.getJSONOutputAsString();
        // TODO: Read all DICOM Tags

        // Get the label information from segment attributes
        vector<map<unsigned, dcmqi::SegmentAttributes *>>::const_iterator segmentIter =
          metaInfo.segmentsAttributesMappingList.begin();
        map<unsigned, dcmqi::SegmentAttributes *> segmentMap = (*segmentIter);
        map<unsigned, dcmqi::SegmentAttributes *>::const_iterator segmentMapIter = (*segmentIter).begin();
        dcmqi::SegmentAttributes *segmentAttr = (*segmentMapIter).second;

        OFString labelName;

        if (segmentAttr->getSegmentedPropertyTypeCodeSequence() != nullptr)
          segmentAttr->getSegmentedPropertyTypeCodeSequence()->getCodeMeaning(labelName);
        else
        {
          labelName = std::to_string(segmentAttr->getLabelID()).c_str();
          if (labelName.empty())
            labelName = "Unnamed";
        }

        float tmp[3] = {0.0, 0.0, 0.0};
        if (segmentAttr->getRecommendedDisplayRGBValue() != nullptr)
        {
          tmp[0] = segmentAttr->getRecommendedDisplayRGBValue()[0] / 255.0;
          tmp[1] = segmentAttr->getRecommendedDisplayRGBValue()[1] / 255.0;
          tmp[2] = segmentAttr->getRecommendedDisplayRGBValue()[2] / 255.0;
        }

        // If labelSetImage do not exists (first image)
        if (labelSetImage.IsNull())
        {
          // Initialize the labelSetImage with the read image
          labelSetImage = LabelSetImage::New();
          labelSetImage->InitializeByLabeledImage(layerImage);
          // Already a label was generated, so set the information to this
          Label *activeLabel = labelSetImage->GetActiveLabel(labelSetImage->GetActiveLayer());
          activeLabel->SetName(labelName.c_str());
          activeLabel->SetColor(Color(tmp));
          activeLabel->SetValue(segValue);
        }
        else
        {
          // Add a new layer to the labelSetImage. Background label is set automatically
          labelSetImage->AddLayer(layerImage);

          // Add new label
          Label *newLabel = new Label;
          newLabel->SetName(labelName.c_str());
          newLabel->SetColor(Color(tmp));
          newLabel->SetValue(segValue);

          labelSetImage->GetLabelSet(labelSetImage->GetActiveLayer())->AddLabel(newLabel);
        }

        ++segmentIter;
      }
      // Clean up
      if (converter != nullptr)
        delete converter;
    }
    catch (const std::exception &e)
    {
      MITK_ERROR << "An error occurred while reading the DICOM Seg file: " << e.what();
      return result;
    }

    // Set active layer to th first layer of the labelset image
    if (labelSetImage->GetNumberOfLayers() > 1 && labelSetImage->GetActiveLayer() != 0)
      labelSetImage->SetActiveLayer(0);

    result.push_back(labelSetImage.GetPointer());

    return result;
  }
Пример #22
0
        virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const
        {
            notice()<<"Reading DICOM file "<<file<<" using DCMTK"<<std::endl;

            std::string ext = osgDB::getLowerCaseFileExtension(file);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
            
            std::string fileName = file;
            if (ext=="dicom")
            {
                fileName = osgDB::getNameLessExtension(file);
            }

            fileName = osgDB::findDataFile( fileName, options );
            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

            Files files;
            
            osgDB::FileType fileType = osgDB::fileType(fileName);
            if (fileType==osgDB::DIRECTORY)
            {
                getDicomFilesInDirectory(fileName, files);
            }
            else
            {
#if 1
                files.push_back(fileName);
#else                            
                if (!getDicomFilesInDirectory(osgDB::getFilePath(fileName), files))
                {
                    files.push_back(fileName);
                }
#endif            
            }

            if (files.empty())
            {
                return ReadResult::FILE_NOT_FOUND;
            }

            osg::ref_ptr<osg::RefMatrix> matrix = new osg::RefMatrix;
            osg::ref_ptr<osg::Image> image;
            unsigned int imageNum = 0;
            EP_Representation pixelRep = EPR_Uint8;
            int numPlanes = 0;
            GLenum pixelFormat = 0;
            GLenum dataType = 0;
            unsigned int pixelSize = 0;
            
            typedef std::list<FileInfo> FileInfoList;
            FileInfoList fileInfoList;

            typedef std::map<double, FileInfo> DistanceFileInfoMap;
            typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap;
            OrientationFileInfoMap orientationFileInfoMap;
            
            unsigned int totalNumSlices = 0;

            for(Files::iterator itr = files.begin();
                itr != files.end();
                ++itr)
            {
                DcmFileFormat fileformat;
                OFCondition status = fileformat.loadFile((*itr).c_str());
                if(!status.good()) return ReadResult::ERROR_IN_READING_FILE;
                
                FileInfo fileInfo;
                fileInfo.filename = *itr;

                double pixelSize_y = 1.0;
                double pixelSize_x = 1.0;
                double sliceThickness = 1.0;
                double imagePositionPatient[3] = {0, 0, 0};
                double imageOrientationPatient[6] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0 };
                Uint16 numOfSlices = 1;
                
                double value = 0.0;
                if (fileformat.getDataset()->findAndGetFloat64(DCM_PixelSpacing, value,0).good())
                {
                    pixelSize_y = value;
                    fileInfo.matrix(1,1) = pixelSize_y;
                }

                if (fileformat.getDataset()->findAndGetFloat64(DCM_PixelSpacing, value,1).good())
                {
                    pixelSize_x = value;
                    fileInfo.matrix(0,0) = pixelSize_x;
                }

                // Get slice thickness
                if (fileformat.getDataset()->findAndGetFloat64(DCM_SliceThickness, value).good())
                {
                    sliceThickness = value;
                    notice()<<"sliceThickness = "<<sliceThickness<<std::endl;
                    fileInfo.sliceThickness = sliceThickness;
                }
    
                notice()<<"tagExistsWithValue(DCM_NumberOfFrames)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfFrames)<<std::endl;
                notice()<<"tagExistsWithValue(DCM_NumberOfSlices)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfSlices)<<std::endl;

                Uint32 numFrames;
                if (fileformat.getDataset()->findAndGetUint32(DCM_NumberOfFrames, numFrames).good())
                {
                    fileInfo.numSlices = numFrames;
                    notice()<<"Read number of frames = "<<numFrames<<std::endl;
                }

                
                OFString numFramesStr;
                if (fileformat.getDataset()->findAndGetOFString(DCM_NumberOfFrames, numFramesStr).good())
                {
                    fileInfo.numSlices = atoi(numFramesStr.c_str());
                    notice()<<"Read number of frames = "<<numFramesStr<<std::endl;
                }

                if (fileformat.getDataset()->findAndGetUint16(DCM_NumberOfFrames, numOfSlices).good())
                {
                    fileInfo.numSlices = numOfSlices;
                    notice()<<"Read number of frames = "<<numOfSlices<<std::endl;
                }
                
                if (fileformat.getDataset()->findAndGetUint16(DCM_NumberOfSlices, numOfSlices).good())
                {
                    fileInfo.numSlices = numOfSlices;
                    notice()<<"Read number of slices = "<<numOfSlices<<std::endl;
                }



                // patient position
                for(int i=0; i<3; ++i)
                {
                    if (fileformat.getDataset()->findAndGetFloat64(DCM_ImagePositionPatient, imagePositionPatient[i],i).good())
                    {
                        notice()<<"Read DCM_ImagePositionPatient["<<i<<"], "<<imagePositionPatient[i]<<std::endl;
                    }
                    else
                    {
                        notice()<<"Have not read DCM_ImagePositionPatient["<<i<<"]"<<std::endl;
                    }
                }
                //notice()<<"imagePositionPatient[2]="<<imagePositionPatient[2]<<std::endl;
                
                fileInfo.matrix.setTrans(imagePositionPatient[0],imagePositionPatient[1],imagePositionPatient[2]);

                for(int i=0; i<6; ++i)
                {
                    double value = 0.0;
                    if (fileformat.getDataset()->findAndGetFloat64(DCM_ImageOrientationPatient, value,i).good())
                    {
                        imageOrientationPatient[i] = value;
                        notice()<<"Read imageOrientationPatient["<<i<<"], "<<imageOrientationPatient[i]<<std::endl;
                    }
                    else
                    {
                        notice()<<"Have not read imageOrientationPatient["<<i<<"]"<<std::endl;
                    }
                }

                osg::Vec3d dirX(imageOrientationPatient[0],imageOrientationPatient[1],imageOrientationPatient[2]);
                osg::Vec3d dirY(imageOrientationPatient[3],imageOrientationPatient[4],imageOrientationPatient[5]);
                osg::Vec3d dirZ = dirX ^ dirY;
                dirZ.normalize();
                
                dirX *= pixelSize_x;
                dirY *= pixelSize_y;
                
                fileInfo.matrix(0,0) = dirX[0];
                fileInfo.matrix(1,0) = dirX[1];
                fileInfo.matrix(2,0) = dirX[2];
                
                fileInfo.matrix(0,1) = dirY[0];
                fileInfo.matrix(1,1) = dirY[1];
                fileInfo.matrix(2,1) = dirY[2];
                
                fileInfo.matrix(0,2) = dirZ[0];
                fileInfo.matrix(1,2) = dirZ[1];
                fileInfo.matrix(2,2) = dirZ[2];
                
                fileInfo.distance = dirZ * (osg::Vec3d(0.0,0.0,0.0)*fileInfo.matrix);

                notice()<<"dirX = "<<dirX<<std::endl;
                notice()<<"dirY = "<<dirY<<std::endl;
                notice()<<"dirZ = "<<dirZ<<std::endl;
                notice()<<"matrix = "<<fileInfo.matrix<<std::endl;
                notice()<<"pos = "<<osg::Vec3d(0.0,0.0,0.0)*fileInfo.matrix<<std::endl;
                notice()<<"dist = "<<fileInfo.distance<<std::endl;
                notice()<<std::endl;

                (orientationFileInfoMap[dirZ])[fileInfo.distance] = fileInfo;

                totalNumSlices += fileInfo.numSlices;

            }

            if (orientationFileInfoMap.empty()) return 0;
            
            typedef std::map<double, FileInfo> DistanceFileInfoMap;
            typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap;
            for(OrientationFileInfoMap::iterator itr = orientationFileInfoMap.begin();
                itr != orientationFileInfoMap.end();
                ++itr)
            {
                notice()<<"Orientation = "<<itr->first<<std::endl;
                DistanceFileInfoMap& dfim = itr->second;
                for(DistanceFileInfoMap::iterator ditr = dfim.begin();
                    ditr != dfim.end();
                    ++ditr)
                {
                    FileInfo& fileInfo = ditr->second;
                    notice()<<"   d = "<<fileInfo.distance<<" "<<fileInfo.filename<<std::endl;
                }
            }
            

            DistanceFileInfoMap& dfim = orientationFileInfoMap.begin()->second;
            if (dfim.empty()) return 0;

            double totalDistance = 0.0;
            if (dfim.size()>1)
            {
                totalDistance = fabs(dfim.rbegin()->first - dfim.begin()->first);
            }
            else
            {
                totalDistance = dfim.begin()->second.sliceThickness * double(dfim.begin()->second.numSlices);
            }
            
            notice()<<"Total Distance including ends "<<totalDistance<<std::endl;

            double averageThickness = totalNumSlices<=1 ? 1.0 : totalDistance / double(totalNumSlices-1);
            
            notice()<<"Average thickness "<<averageThickness<<std::endl;

            for(DistanceFileInfoMap::iterator ditr = dfim.begin();
                ditr != dfim.end();
                ++ditr)
            {
                FileInfo& fileInfo = ditr->second;
                
                std::auto_ptr<DicomImage> dcmImage(new DicomImage(fileInfo.filename.c_str()));
                if (dcmImage.get())
                {
                    if (dcmImage->getStatus()==EIS_Normal)
                    {

                        // get the pixel data
                        const DiPixel* pixelData = dcmImage->getInterData();
                        if(!pixelData) 
                        {
                            warning()<<"Error: no data in DicomImage object."<<std::endl;
                            return ReadResult::ERROR_IN_READING_FILE;
                        }
                        
                        osg::ref_ptr<osg::Image> imageAdapter = new osg::Image;
                        
                        EP_Representation curr_pixelRep;
                        int curr_numPlanes;
                        GLenum curr_pixelFormat;
                        GLenum curr_dataType;
                        unsigned int curr_pixelSize;

                        // create the new image
                        convertPixelTypes(pixelData,
                                          curr_pixelRep, curr_numPlanes, 
                                          curr_dataType, curr_pixelFormat, curr_pixelSize);

                        imageAdapter->setImage(dcmImage->getWidth(), dcmImage->getHeight(), dcmImage->getFrameCount(),
                                              curr_pixelFormat,
                                              curr_pixelFormat,
                                              curr_dataType,
                                              (unsigned char*)(pixelData->getData()),
                                              osg::Image::NO_DELETE);
                        if (!image)
                        {
                            pixelRep = curr_pixelRep;
                            numPlanes = curr_numPlanes;
                            dataType = curr_dataType;
                            pixelFormat = curr_pixelFormat;
                            pixelSize = curr_pixelSize;

                            (*matrix)(0,0) = fileInfo.matrix(0,0);
                            (*matrix)(1,0) = fileInfo.matrix(1,0);
                            (*matrix)(2,0) = fileInfo.matrix(2,0);
                            (*matrix)(0,1) = fileInfo.matrix(0,1);
                            (*matrix)(1,1) = fileInfo.matrix(1,1);
                            (*matrix)(2,1) = fileInfo.matrix(2,1);
                            (*matrix)(0,2) = fileInfo.matrix(0,2) * averageThickness;
                            (*matrix)(1,2) = fileInfo.matrix(1,2) * averageThickness;
                            (*matrix)(2,2) = fileInfo.matrix(2,2) * averageThickness;
                            

                            
                            image = new osg::Image;
                            image->setUserData(matrix.get());
                            image->setFileName(fileName.c_str());
                            image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, 
                                                 pixelFormat, dataType);
                                                 
                                                 
                            matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r())));

                            notice()<<"Image dimensions = "<<image->s()<<", "<<image->t()<<", "<<image->r()<<" pixelFormat=0x"<<std::hex<<pixelFormat<<" dataType=0x"<<std::hex<<dataType<<std::dec<<std::endl;
                        }
                        else if (pixelData->getPlanes()>numPlanes ||
                                 pixelData->getRepresentation()>pixelRep)
                        {
                            notice()<<"Need to reallocated "<<image->s()<<", "<<image->t()<<", "<<image->r()<<std::endl;
                            
                            // record the previous image settings to use when we copy back the content.
                            osg::ref_ptr<osg::Image> previous_image = image;

                            // create the new image
                            convertPixelTypes(pixelData,
                                              pixelRep, numPlanes, 
                                              dataType, pixelFormat, pixelSize);
                                              
                            image = new osg::Image;
                            image->setUserData(previous_image->getUserData());
                            image->setFileName(fileName.c_str());
                            image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, 
                                                 pixelFormat, dataType);
                                                 
                            osg::copyImage(previous_image.get(), 0,0,0, previous_image->s(), previous_image->t(), imageNum,
                                           image.get(), 0, 0, 0,                                                 
                                           false);
                            
                        }
                        
                        osg::copyImage(imageAdapter.get(), 0,0,0, imageAdapter->s(), imageAdapter->t(), imageAdapter->r(), 
                                       image.get(), 0, 0, imageNum,
                                       false);
                                             
                        imageNum += dcmImage->getFrameCount();
                    }
                    else
                    {
                        warning()<<"Error in reading dicom file "<<fileName.c_str()<<", error = "<<DicomImage::getString(dcmImage->getStatus())<<std::endl;
                    }
                }
            }
            
            if (!image)
            {
                return ReadResult::ERROR_IN_READING_FILE;
            }

            notice()<<"Spacing = "<<*matrix<<std::endl;
            
            return image.get();
        }
  void DICOMSegmentationIO::Write()
  {
    ValidateOutputLocation();

    mitk::LocaleSwitch localeSwitch("C");
    LocalFile localFile(this);
    const std::string path = localFile.GetFileName();

    auto input = dynamic_cast<const LabelSetImage *>(this->GetInput());
    if (input == nullptr)
      mitkThrow() << "Cannot write non-image data";

    // Get DICOM information from referenced image
    vector<DcmDataset *> dcmDatasets;
    DcmFileFormat *readFileFormat = new DcmFileFormat();
    try
    {
      // TODO: Generate dcmdataset witk DICOM tags from property list; ATM the source are the filepaths from the
      // property list
      mitk::StringLookupTableProperty::Pointer filesProp =
        dynamic_cast<mitk::StringLookupTableProperty *>(input->GetProperty("files").GetPointer());

      if (filesProp.IsNull())
      {
        mitkThrow() << "No property with dicom file path.";
        return;
      }

      StringLookupTable filesLut = filesProp->GetValue();
      const StringLookupTable::LookupTableType &lookUpTableMap = filesLut.GetLookupTable();

      for (auto it : lookUpTableMap)
      {
        const char *fileName = (it.second).c_str();
        if (readFileFormat->loadFile(fileName, EXS_Unknown).good())
          dcmDatasets.push_back(readFileFormat->getAndRemoveDataset());
      }
    }
    catch (const std::exception &e)
    {
      MITK_ERROR << "An error occurred while getting the dicom informations: " << e.what() << endl;
      return;
    }

    // Iterate over all layers. For each a dcm file will be generated
    for (unsigned int layer = 0; layer < input->GetNumberOfLayers(); ++layer)
    {
      vector<itkInternalImageType::Pointer> segmentations;

      try
      {
        // Cast mitk layer image to itk
        ImageToItk<itkInputImageType>::Pointer imageToItkFilter = ImageToItk<itkInputImageType>::New();
        // BUG: It must be the layer image, but there are some errors with it (dcmqi: generate the dcmSeg "No frame data
        // available") --> input->GetLayerImage(layer)
        imageToItkFilter->SetInput(input);
        imageToItkFilter->Update();

        // Cast from original itk type to dcmqi input itk image type
        typedef itk::CastImageFilter<itkInputImageType, itkInternalImageType> castItkImageFilterType;
        castItkImageFilterType::Pointer castFilter = castItkImageFilterType::New();
        castFilter->SetInput(imageToItkFilter->GetOutput());
        castFilter->Update();

        itkInternalImageType::Pointer itkLabelImage = castFilter->GetOutput();
        itkLabelImage->DisconnectPipeline();

        // Iterate over all labels. For each a segmentation image will be created
        const LabelSet *labelSet = input->GetLabelSet(layer);
        for (auto itLabel = labelSet->IteratorConstBegin(); itLabel != labelSet->IteratorConstEnd(); ++itLabel)
        {
          // Thresold over the image with the given label value
          itk::ThresholdImageFilter<itkInternalImageType>::Pointer thresholdFilter =
            itk::ThresholdImageFilter<itkInternalImageType>::New();
          thresholdFilter->SetInput(itkLabelImage);
          thresholdFilter->ThresholdOutside(itLabel->first, itLabel->first);
          thresholdFilter->SetOutsideValue(0);
          thresholdFilter->Update();
          itkInternalImageType::Pointer segmentImage = thresholdFilter->GetOutput();
          segmentImage->DisconnectPipeline();

          segmentations.push_back(segmentImage);
        }
      }
      catch (const itk::ExceptionObject &e)
      {
        MITK_ERROR << e.GetDescription() << endl;
        return;
      }

      // Create segmentation meta information
      const std::string &tmpMetaInfoFile = this->CreateMetaDataJsonFile(layer);

      MITK_INFO << "Writing image: " << path << std::endl;
      try
      {
        // Convert itk segmentation images to dicom image
        dcmqi::ImageSEGConverter *converter = new dcmqi::ImageSEGConverter();
        DcmDataset *result = converter->itkimage2dcmSegmentation(dcmDatasets, segmentations, tmpMetaInfoFile);

        // Write dicom file
        DcmFileFormat dcmFileFormat(result);

        std::string filePath = path.substr(0, path.find_last_of("."));
        // If there is more than one layer, we have to write more than 1 dicom file
        if (input->GetNumberOfLayers() != 1)
          filePath = filePath + std::to_string(layer) + ".dcm";
        else
          filePath = filePath + ".dcm";

        dcmFileFormat.saveFile(filePath.c_str(), EXS_LittleEndianExplicit);

        // Clean up
        if (converter != nullptr)
          delete converter;
        if (result != nullptr)
          delete result;
      }
      catch (const std::exception &e)
      {
        MITK_ERROR << "An error occurred during writing the DICOM Seg: " << e.what() << endl;
        return;
      }
    } // Write a dcm file for the next layer

    // End of image writing; clean up
    if (readFileFormat)
      delete readFileFormat;

    for (auto obj : dcmDatasets)
      delete obj;
    dcmDatasets.clear();
  }
Пример #24
0
/* Load the data from a DICOM file */
Dicom::Dicom(std::string path) : filename(path), valid(false) {

        // Load the image as a DcmFileFormat 
        DcmFileFormat fileFormat;
        OFCondition status = fileFormat.loadFile(path.c_str());
        if (status.bad()) {
                SIFT3D_ERR("Dicom.Dicom: failed to read DICOM file %s (%s)\n",
                        path.c_str(), status.text());
                return;
        }

        // Get the dataset
        DcmDataset *const data = fileFormat.getDataset();

        // Get the series UID 
        const char *seriesUIDStr;
        status = data->findAndGetString(DCM_SeriesInstanceUID, seriesUIDStr);
        if (status.bad() || seriesUIDStr == NULL) {
                SIFT3D_ERR("Dicom.Dicom: failed to get SeriesInstanceUID "
                        "from file %s (%s)\n", path.c_str(), status.text());
                return;
        }
        seriesUID = std::string(seriesUIDStr); 

#if 0
        // Read the patient position
        const char *patientPosStr;
        status = data->findAndGetString(DCM_PatientPosition, patientPosStr);
        if (status.bad() || patientPosStr == NULL) {
                std::cerr << "Dicom.Dicom: failed to get PatientPosition " <<
                        "from file " << path << " (" << status.text() << ")" <<
                        std::endl;
                return;
        }

        // Interpret the patient position to give the sign of the z axis
        double zSign;
        switch (patientPosStr[0]) {
        case 'H':
                zSign = -1.0;
                break;
        case 'F':
                zSign = 1.0;
                break;
        default:
                std::cerr << "Dicom.Dicom: unrecognized patient position: " <<
                        patientPosStr << std::endl;
                return;
        }
#else
        //TODO: Is this needed?
        const double zSign = 1.0;
#endif

        // Read the image position patient vector
        const char *imPosPatientStr;
        status = data->findAndGetString(DCM_ImagePositionPatient, 
                imPosPatientStr);
        if (status.bad() || imPosPatientStr == NULL) {
                SIFT3D_ERR("Dicom.Dicom: failed to get ImagePositionPatient "
                        "from file %s (%s)\n", path.c_str(), status.text());
                return;
        }

        // Parse the image position patient vector to get the z coordinate
        double imPosZ;
        if (sscanf(imPosPatientStr, "%*f\\%*f\\%lf", &imPosZ) != 1) {
                SIFT3D_ERR("Dicom.Dicom: failed to parse "
                        "ImagePositionPatient tag %s from file %s\n", 
                        imPosPatientStr, path.c_str());
                return;
        }

        // Compute the z-location of the upper-left corner, in feet-first 
        // coordinates
        z = zSign * imPosZ;

        // Load the DicomImage object
        DicomImage dicomImage(path.c_str());
        if (dicomImage.getStatus() != EIS_Normal) {
                SIFT3D_ERR("Dicom.Dicom: failed to open image %s (%s)\n",
                        path.c_str(), 
                        DicomImage::getString(dicomImage.getStatus()));
                return;
        }

        // Check for color images
        if (!dicomImage.isMonochrome()) {
                SIFT3D_ERR("Dicom.Dicom: reading of color DICOM images is "
                        "not supported at this time \n");
                return;
        }
        nc = 1;

        // Read the dimensions
        nx = dicomImage.getWidth();
        ny = dicomImage.getHeight();
        nz = dicomImage.getFrameCount();
        if (nx < 1 || ny < 1 || nz < 1) {
                SIFT3D_ERR("Dicom.Dicom: invalid dimensions for file %s "
                        "(%d, %d, %d)\n", path.c_str(), nx, ny, nz);
                return;
        }

        // Read the pixel spacing
        const char *pixelSpacingStr;
        status = data->findAndGetString(DCM_PixelSpacing, pixelSpacingStr);
        if (status.bad()) {
                SIFT3D_ERR("Dicom.Dicom: failed to get pixel spacing from "
                        "file %s (%s)\n", path.c_str(), status.text());
                return;
        }
        if (sscanf(pixelSpacingStr, "%lf\\%lf", &ux, &uy) != 2) {
                SIFT3D_ERR("Dicom.Dicom: unable to parse pixel spacing from "
                        "file %s \n", path.c_str());
                return;
        }
        if (ux <= 0.0 || uy <= 0.0) {
                SIFT3D_ERR("Dicom.Dicom: file %s has invalid pixel spacing "
                        "[%f, %f]\n", path.c_str(), ux, uy);
                return;
        }

        // Read the slice thickness 
        Float64 sliceThickness;
        status = data->findAndGetFloat64(DCM_SliceThickness, sliceThickness);
        if (!status.good()) {
                SIFT3D_ERR("Dicom.Dicom: failed to get slice thickness from "
                        "file %s (%s)\n", path.c_str(), status.text());
                return;
        }

        // Convert to double 
        uz = sliceThickness;
        if (uz <= 0.0) {
                SIFT3D_ERR("Dicom.Dicom: file %s has invalid slice "
                        "thickness: %f \n", path.c_str(), uz);
                return;
        }
        
        // Set the window 
        dicomImage.setMinMaxWindow();

        valid = true;
}
void mitk::DICOMDCMTKTagScanner::Scan()
{
  this->PushLocale();

  try
  {
    DcmPathProcessor processor;
    processor.setItemWildcardSupport(true);

    DICOMGenericTagCache::Pointer newCache = DICOMGenericTagCache::New();

    for (const auto& fileName : this->m_InputFilenames)
    {
      DcmFileFormat dfile;
      OFCondition cond = dfile.loadFile(fileName.c_str());
      if (cond.bad())
      {
        MITK_ERROR << "Error when scanning for tags. Cannot open given file. File: " << fileName;
      }
      else
      {
        DICOMGenericImageFrameInfo::Pointer info = DICOMGenericImageFrameInfo::New(fileName);

        for (const auto& path : this->m_ScannedTags)
        {
          std::string tagPath = DICOMTagPathToDCMTKSearchPath(path);
          cond = processor.findOrCreatePath(dfile.getDataset(), tagPath.c_str());
          if (cond.good())
          {
            OFList< DcmPath * > findings;
            processor.getResults(findings);
            for (const auto& finding : findings)
            {
              auto element = dynamic_cast<DcmElement*>(finding->back()->m_obj);
              if (!element)
              {
                auto item = dynamic_cast<DcmItem*>(finding->back()->m_obj);
                if (item)
                {
                  element = item->getElement(finding->back()->m_itemNo);
                }
              }

              if (element)
              {
                OFString value;
                cond = element->getOFStringArray(value);
                if (cond.good())
                {
                  info->SetTagValue(DcmPathToTagPath(finding), std::string(value.c_str()));
                }
              }
            }
          }
        }
        newCache->AddFrameInfo(info);
      }
    }

    m_Cache = newCache;

    this->PopLocale();
  }
  catch (...)
  {
    this->PopLocale();
    throw;
  }
}
Пример #26
0
void SortDcmFile::sortFile(const char url[])
{
	QDir *dir=new QDir(url);
	QStringList filter;
	DcmFileFormat fileformat;
	OFString tempinfo;
	QString FileAddress = QString(url);

	
	//如果重名
	SortDcmFile::changName(url);


	//获取目录下所有文件名(含两个目录名)
	QList<QFileInfo> *fileInfo=new QList<QFileInfo>(dir->entryInfoList(filter));
	QList<dicomInfo> sortInfo;
	//获取dicom信息
	for(int i = 2 ; i < fileInfo->count() ; ++i)
	{
		dicomInfo temp;
		temp.filename = fileInfo->at(i).fileName();
		QByteArray ba = fileInfo->at(i).filePath().toLatin1();
		char *url = ba.data();
		OFCondition os=fileformat.loadFile(url);
		if(os.good())
		{
			if((fileformat.getDataset()->findAndGetOFString(DcmTagKey(0x0020,0x0013),tempinfo)).good())
			{
				
				temp.imageID=tempinfo;
				//cout<<temp.imageID<<endl;

			}else
			{
				cout<<"No Find"<<endl;
			}
			if(fileformat.getDataset()->findAndGetOFString(DcmTagKey(0x0020,0x1041),tempinfo).good())
			{
				
				temp.sliceLocation=OFtoSignal(tempinfo);

			}else
			{
				cout<<"No Find"<<endl;
			}
			sortInfo.push_back(temp);
			

		}
	}

	sort(sortInfo.begin(),sortInfo.end(),cmp);

	QList<dicomInfo>::iterator it;


	//分组
	double tempbef=9999;
	int group=0;
	int group_number=-1;
	//QList<dicomInfo>::iterator it;
	for(it=sortInfo.begin();it!=sortInfo.end();it++)
	{
		if(it->sliceLocation>tempbef)
		{
			group++;
			SortDcmFile::Pslice = group_number+1;
			group_number=0;
			tempbef=9999;
			
		}else
		{
			tempbef=it->sliceLocation;
			group_number++;
		}
        SortDcmFile::PsetNum = group+1;
		QFile::rename( FileAddress+it->filename ,FileAddress+"IM"+QString::fromStdString(itos(group))+"-"+QString::fromStdString(itos(group_number)));
	}
}
Пример #27
0
void ImageInstance::initImage(const QString &file)
{
    DcmFileFormat dcmFile;
    OFCondition result;

    result = dcmFile.loadFile(file.toLocal8Bit());
    DcmDataset *dset = dcmFile.getDataset();

    if (result.good()) {
        //patient information
        const char *value = NULL;
        result = dset->findAndGetString(DCM_PatientID, value);
        patientID = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_PatientName, value);
        patientName = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_PatientAge, value);
        patientAge = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_PatientBirthDate, value);
        patientBirth = QDate::fromString(QString::fromLocal8Bit(value),
                                         DATE_DICOM_FORMAT);

        result = dset->findAndGetString(DCM_PatientSex, value);
        patientSex = QString::fromLocal8Bit(value);

        //study information
        result = dset->findAndGetString(DCM_StudyInstanceUID, value);
        studyUid = QString::fromLatin1(value);

        result = dset->findAndGetString(DCM_StudyDate, value);
        studyTime.setDate(QDate::fromString(QString::fromLocal8Bit(value),
                                            DATE_DICOM_FORMAT));

        result = dset->findAndGetString(DCM_StudyTime, value);
        studyTime.setTime(formatDicomTime(QString::fromLatin1(value)));

        result = dset->findAndGetString(DCM_StudyDescription, value);
        studyDes = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_ProtocolName, value);
        procId = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_BodyPartExamined, value);
        bodyPart = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_Manufacturer, value);
        manufacturer = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_Modality, value);
        modality = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_StationName, value);
        stationName = QString::fromLocal8Bit(value);

        //series information
        result = dset->findAndGetString(DCM_SeriesInstanceUID, value);
        seriesUid = QString::fromLatin1(value);

        result = dset->findAndGetString(DCM_SeriesNumber, value);
        seriesNumber = QString::fromLatin1(value);

        result = dset->findAndGetString(DCM_SeriesDescription, value);
        seriesDes = QString::fromLocal8Bit(value);

        //instance information
        result = dset->findAndGetString(DCM_SOPClassUID, value);
        sopClassUid = QString::fromLatin1(value);

        result = dset->findAndGetString(DCM_SOPInstanceUID, value);
        instanceUid = QString::fromLatin1(value);

        result = dset->findAndGetString(DCM_InstanceNumber, value);
        instanceNumber = QString::fromLatin1(value);

        result = dset->findAndGetString(DCM_InstitutionName, value);
        institution = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_AcquisitionDate, value);
        if (value==NULL) result = dset->findAndGetString(DCM_ContentDate, value);
        acquisitionTime.setDate(QDate::fromString(QString::fromLatin1(value),
                                                  DATE_DICOM_FORMAT));

        result = dset->findAndGetString(DCM_AcquisitionTime, value);
        if (value==NULL) result = dset->findAndGetString(DCM_ContentTime, value);
        acquisitionTime.setTime(formatDicomTime(QString::fromLatin1(value)));

        result = dset->findAndGetString(DCM_PatientPosition, value);
        patientPostion = QString::fromLatin1(value);

        result = dset->findAndGetString(DCM_RequestingPhysician, value);
        reqPhysician = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_PerformingPhysicianName, value);
        perPhysician = QString::fromLocal8Bit(value);

        result = dset->findAndGetString(DCM_AccessionNumber, value);
        accessionNumber = QString::fromLatin1(value);

        result = dset->findAndGetFloat64(DCM_PixelSpacing, pixelSpacingY, 0);
        result = dset->findAndGetFloat64(DCM_PixelSpacing, pixelSpacingX, 1);

        result = dset->findAndGetString(DCM_KVP, value);
        kvp = QString::fromLatin1(value).toDouble();
        result = dset->findAndGetString(DCM_Exposure, value);
        mAs = QString::fromLatin1(value).toInt();

        result = dset->findAndGetFloat64(DCM_WindowWidth, winWidth);
        result = dset->findAndGetFloat64(DCM_WindowCenter, winCenter);
        defCenter = winCenter;
        defWidth = winWidth;

        if (UID_DigitalXRayImageStorageForPresentation == sopClassUid) {
            DcmItem *refItem;
            const char *refImageUid;
            dset->findAndGetSequenceItem(DCM_ReferencedImageSequence, refItem);
            if (refItem && refItem->findAndGetString(DCM_ReferencedSOPInstanceUID, refImageUid).good()) {
                QString dirName = file.left(file.lastIndexOf('/'));
                rawFile = QString("%1/%2_%3.dcm").arg(dirName, RAW_IMAGE_PREFIX, refImageUid);
                rawCenter = winCenter;
                rawWidth = winWidth;
            }
        }
    }

    dcmImage = new DicomImage(dset, dset->getOriginalXfer());
    if (dcmImage->getStatus() == EIS_Normal) {
        //dcmImage->getWindow(winCenter, winWidth);
        getPixmap(cachedPixmap);
    }
}
Пример #28
0
bool Dicom::DicomReader::OpenDicoms(const std::list<std::string>& dcms)
{
	if (m_pImageData)
	{
		//已经打开了数据
		return false;
	}

	std::map<int,DcmFileFormat*> mapDcms;

	int iMaxLayer = -1;
	int iMinLayer = INT_MAX;

	{
		//获取图像数据
		std::list<std::string>::const_iterator iter = dcms.begin();
		while (iter != dcms.end())
		{
			DcmFileFormat* pDcmFile = new DcmFileFormat();
			OFCondition cond = pDcmFile->loadFile(iter->c_str());
			if (cond.bad())
			{
				delete pDcmFile;
				++iter;
				continue;
			}

			DcmDataset* pDataset = pDcmFile->getDataset();

			Uint16 iC = 0, iR = 0, iB = 0;
			pDataset->findAndGetUint16(DCM_Columns, iC);
			pDataset->findAndGetUint16(DCM_Rows, iR);
			pDataset->findAndGetUint16(DCM_BitsAllocated, iB);
			if (mapDcms.size()<1)
			{
				m_iColumns = iC;
				m_iRows = iR;
				m_iBits = iB;
			}

			if (iC != m_iColumns || iR != m_iRows || iB != m_iBits)
			{
				delete pDcmFile;
				++iter;
				continue;
			}

			Sint32 iL = -1;

			pDataset->findAndGetSint32(DCM_InstanceNumber, iL);
			if (iL>-1 && mapDcms.find(iL) == mapDcms.end())
			{
				mapDcms[iL] = pDcmFile;
				if (iL > iMaxLayer)
					iMaxLayer = iL;
				if (iL < iMinLayer)
					iMinLayer = iL;
			}
			else
			{
				delete pDcmFile;
			}

			++iter;
		}

		if (m_iBits != 16)
			return false;
	}


	//总层数
	m_iLayers = iMaxLayer-iMinLayer+1;
	m_pImageData = new Image::ImageData<short>(m_iRows, m_iColumns, m_iLayers);
	Image::ImageData<short>* pImageShort = reinterpret_cast<Image::ImageData<short>*>(m_pImageData);
	char* pDataPtr = m_pImageData->GetDataPtr();

	{
		//设置图像数据
		std::map<int, DcmFileFormat*>::iterator iter = mapDcms.begin();
		while (iter != mapDcms.end())
		{
			DcmFileFormat* pDcmFile = iter->second;
			DcmDataset* pDataSet = pDcmFile->getDataset();
			{
				const Uint16* pSrcData = NULL;
				unsigned long iCount = 0;
				pDataSet->findAndGetUint16Array(DCM_PixelData, pSrcData, &iCount);
				if (iCount == pImageShort->GetX()*pImageShort->GetY())
				{
					memcpy(pDataPtr+(iCount*2*(iter->first-iMinLayer)), pSrcData, iCount * 2);
				}
				else
				{
					assert("Read dicom error!");
				}
			}
			delete pDcmFile;

			++iter;
		}

		mapDcms.clear();
	}

	m_pImageData->UpdateData();

	return true;
}
Пример #29
0
void QtDcmManager::makePreview ( const QString &filename )
{
    DcmRLEDecoderRegistration::registerCodecs ( OFFalse, OFFalse );
    DJDecoderRegistration::registerCodecs ( EDC_photometricInterpretation, EUC_default, EPC_default, OFFalse );
    DcmFileFormat file;
    file.loadFile ( filename.toLatin1().data() );
    DcmDataset * dset = file.getDataset();
    DicomImage* dcimage = new DicomImage ( dset, file.getDataset()->getOriginalXfer(), CIF_MayDetachPixelData );


    if ( dcimage != NULL ) {
        dcimage->setNoDisplayFunction();
        dcimage->hideAllOverlays();
        dcimage->setNoVoiTransformation();

        if ( dcimage->getStatus() == EIS_Normal ) {
            Uint32 *pixelData = ( Uint32 * ) ( dcimage->getOutputData ( 32 /* bits per sample */ ) );

            if ( pixelData != NULL ) {
                Uint8 *colored = new Uint8[dcimage->getWidth() * dcimage->getHeight() * 4]; //4 * dcimage->getWidth() * dcimage->getHeight() matrix
                Uint8 *col = colored;
                Uint32 *p = pixelData;
                //get the highest values for RGBA, then use them to scale the pixel luminosity
                Uint32 p_max = 0;
#ifdef WIN32                
                Uint32 p_min = UINT_LEAST32_MAX;
#else
                Uint32 p_min = std::numeric_limits<Uint32>::max();
#endif                

                for ( unsigned i = 0; i < dcimage->getWidth(); ++i ) {
                    for ( unsigned j = 0; j < dcimage->getHeight(); ++j, ++p ) {
                        if ( *p > p_max ) {
                            p_max = *p;
                        }
                        
                        if ( *p < p_min ) {
                            p_min = *p;
                        }
                    }
                }

                double a = 4294967295.f / ( ( double ) p_max - ( double ) p_min );

                //re-initialize 'col'
                p = pixelData;
                //copy the pixels in our QImage

                for ( unsigned i = 0; i < dcimage->getWidth(); ++i ) {
                    for ( unsigned j = 0; j < dcimage->getHeight(); ++j, ++p ) {
                        *col = ( Uint8 ) ( ( 255.f / 4294967295.f ) * ( a * ( ( double ) ( *p ) - ( double ) p_min ) ) );
                        ++col;
                        *col = ( Uint8 ) ( ( 255.f / 4294967295.f ) * ( a * ( ( double ) ( *p ) - ( double ) p_min ) ) );
                        ++col;
                        *col = ( Uint8 ) ( ( 255.f / 4294967295.f ) * ( a * ( ( double ) ( *p ) - ( double ) p_min ) ) );
                        ++col;
                        *col = 255;
                        ++col;
                    }
                }

                QImage image ( colored, dcimage->getWidth(), dcimage->getHeight(), QImage::Format_ARGB32 );

                if ( d->previewWidget ) {
                    d->previewWidget->imageLabel->setPixmap ( QPixmap::fromImage ( image.scaled ( 130,130 ), Qt::AutoColor ) );
                }

                delete[] colored;

            }
        }

        delete dcimage;
    }
    
    DcmRLEDecoderRegistration::cleanup();
    DJDecoderRegistration::cleanup();
}
Пример #30
0
void dcm2img(boost::filesystem::path filename, int clientWidth, int clientHeight, wxImage &image)
{
	OFLog::configure(OFLogger::OFF_LOG_LEVEL);	
		
	unsigned char *source = NULL;

	try
	{
		DcmFileFormat dfile;
		if (dfile.loadFile(filename.c_str(), EXS_Unknown, EGL_withoutGL).bad())
			throw std::runtime_error("");
		if(dfile.loadAllDataIntoMemory().bad())
			throw std::runtime_error("");

		// uncompress
		DicomImage di(&dfile, EXS_Unknown);

		if(di.getStatus() != EIS_Normal)
			throw std::runtime_error("");

		di.getFirstFrame();
		di.showAllOverlays();			
		if (di.isMonochrome())
		{
			if(di.getWindowCount())
				di.setWindow(0);
			else
				di.setHistogramWindow();
		}
		
		// don't use di.createScaledImage, it is broken!!

		unsigned int width = di.getWidth();
		unsigned int height = di.getHeight();

		if(!image.Create(width, height, true))
			throw std::runtime_error("");
		
		source = new unsigned char[width * height * 4];		

		di.createWindowsDIB((void * &)source, width * height * 4, 0, 32);			
		
		wxImagePixelData data(image);
		wxImagePixelData::Iterator p(data);
		for(int j = 0; j < height; j++)
		{			
			for(int i = 0; i < width; i++)
			{
				p.MoveTo(data, i, j);
				p.Red() = source[(width * j + i) * 4 + 2];
				p.Green() = source[(width * j + i) * 4 + 1];
				p.Blue() = source[(width * j + i) * 4];
			}
		}	
		
		// scale
		float widthFactor = (float) clientWidth / (float) width;
        float heightFactor = (float) clientHeight / (float) height;

		float scaleFactor = 0;
        if (widthFactor < heightFactor) 
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;

        int scaledWidth  = width * scaleFactor;
        int scaledHeight = height * scaleFactor;

		image.Rescale(scaledWidth, scaledHeight);
	}
	catch(...)
	{

	}

	if(source != NULL)
		delete source;
	
}