Ejemplo n.º 1
0
void vtkApplyLookupTableOnScalarsFast(vtkMitkLevelWindowFilter *self,
                                      vtkImageData *inData,
                                      vtkImageData *outData,
                                      int outExt[6],
                                      T *)
{
    vtkImageIterator<T> inputIt(inData, outExt);
    vtkImageIterator<unsigned char> outputIt(outData, outExt);

    double tableRange[2];

    // access vtkLookupTable
    vtkLookupTable* lookupTable = dynamic_cast<vtkLookupTable*>(self->GetLookupTable());
    lookupTable->GetTableRange(tableRange);

    // access elements of the vtkLookupTable
    int * realLookupTable = reinterpret_cast<int*>(lookupTable->GetTable()->GetPointer(0));
    int maxIndex = lookupTable->GetNumberOfColors() - 1;


    float scale = (tableRange[1] -tableRange[0] > 0 ? (maxIndex + 1) / (tableRange[1] - tableRange[0]) : 0.0);
    // ensuring that starting point is zero
    float bias = - tableRange[0] * scale;
    // due to later conversion to int for rounding
    bias += 0.5f;


    // Loop through ouput pixels
    while (!outputIt.IsAtEnd())
    {
        unsigned char* outputSI = outputIt.BeginSpan();
        unsigned char* outputSIEnd = outputIt.EndSpan();

        T* inputSI = inputIt.BeginSpan();

        while (outputSI != outputSIEnd)
        {
            // map to an index
            int idx = static_cast<int>( *inputSI * scale + bias );

            if (idx < 0)
                idx = 0;
            else if (idx > maxIndex)
                idx = maxIndex;

            * reinterpret_cast<int*>(outputSI) = realLookupTable[idx];

            inputSI++;
            outputSI+=4;
        }

        inputIt.NextSpan();
        outputIt.NextSpan();
    }
}
void
AdditiveRicianNoiseImageFilter<TInputImage, TOutputImage>
::ThreadedGenerateData( const OutputImageRegionType &outputRegionForThread,
		ThreadIdType threadId)
{
	InputImageConstPointer  inputPtr = this->GetInput();
	OutputImagePointer outputPtr = this->GetOutput(0);

	// create 2 random generators per thread
	typename Statistics::NormalVariateGenerator::Pointer rand = Statistics::NormalVariateGenerator::New();



	rand->Initialize(std::rand());

	// Define the portion of the input to walk for this thread, using
	// the CallCopyOutputRegionToInputRegion method allows for the input
	// and output images to be different dimensions
	InputImageRegionType inputRegionForThread;
	this->CallCopyOutputRegionToInputRegion(inputRegionForThread, outputRegionForThread);

	// Define the iterators
	ImageRegionConstIterator<TInputImage>  inputIt(inputPtr, inputRegionForThread);
	ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread);

	ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels());

	inputIt.GoToBegin();
	outputIt.GoToBegin();


	while( !inputIt.IsAtEnd() )
	{
		// get the variables
		double value = inputIt.Get();

		double c1 = m_Mean + m_StandardDeviation * rand->GetVariate();
		double c2 = m_Mean + m_StandardDeviation * rand->GetVariate();

		// compute the output value
		double out = sqrt(((value + c1) * (value + c1)) + (c2 * c2));


	//	std::cout << value << " " << out << std::endl;

		out = std::min( (double)NumericTraits<OutputImagePixelType>::max(), out );
		out = std::max( (double)NumericTraits<OutputImagePixelType>::NonpositiveMin(), out );
		outputIt.Set( (OutputImagePixelType) out  );
		++inputIt;
		++outputIt;
		progress.CompletedPixel();  // potential exception thrown here
	}
}
Ejemplo n.º 3
0
void mitk::MaskImageFilter::InternalComputeMask(itk::Image<TPixel, VImageDimension>* inputItkImage)
{
  typedef itk::Image<TPixel, VImageDimension> ItkInputImageType;
  typedef itk::Image<unsigned char, VImageDimension> ItkMaskImageType;
  typedef itk::Image<TPixel, VImageDimension> ItkOutputImageType;
  
  typedef itk::ImageRegionConstIterator< ItkInputImageType > ItkInputImageIteratorType;
  typedef itk::ImageRegionConstIterator< ItkMaskImageType > ItkMaskImageIteratorType;
  typedef itk::ImageRegionIteratorWithIndex< ItkOutputImageType > ItkOutputImageIteratorType;

  typename mitk::ImageToItk<ItkMaskImageType>::Pointer maskimagetoitk = mitk::ImageToItk<ItkMaskImageType>::New();
  maskimagetoitk->SetInput(m_MaskTimeSelector->GetOutput());
  maskimagetoitk->Update();
  typename ItkMaskImageType::Pointer maskItkImage = maskimagetoitk->GetOutput();

  typename mitk::ImageToItk<ItkOutputImageType>::Pointer outputimagetoitk = mitk::ImageToItk<ItkOutputImageType>::New();
  outputimagetoitk->SetInput(m_OutputTimeSelector->GetOutput());
  outputimagetoitk->Update();
  typename ItkOutputImageType::Pointer outputItkImage = outputimagetoitk->GetOutput();

  // create the iterators
  typename ItkInputImageType::RegionType inputRegionOfInterest = inputItkImage->GetLargestPossibleRegion();
  ItkInputImageIteratorType  inputIt( inputItkImage, inputRegionOfInterest );
  ItkMaskImageIteratorType  maskIt ( maskItkImage, inputRegionOfInterest );
  ItkOutputImageIteratorType outputIt( outputItkImage, inputRegionOfInterest );

  //typename ItkOutputImageType::PixelType outsideValue = itk::NumericTraits<typename ItkOutputImageType::PixelType>::min();
  if ( !m_OverrideOutsideValue )
    m_OutsideValue = itk::NumericTraits<typename ItkOutputImageType::PixelType>::min();

   m_MinValue = (float)(itk::NumericTraits<typename ItkOutputImageType::PixelType>::max());
   m_MaxValue = (float)(itk::NumericTraits<typename ItkOutputImageType::PixelType>::min());


  for ( inputIt.GoToBegin(), maskIt.GoToBegin(), outputIt.GoToBegin(); !inputIt.IsAtEnd() && !maskIt.IsAtEnd(); ++inputIt, ++maskIt, ++outputIt)
  {
    if ( maskIt.Get() > itk::NumericTraits<typename ItkMaskImageType::PixelType>::Zero )
    {
      outputIt.Set(inputIt.Get());
      m_MinValue = vnl_math_min((float)inputIt.Get(), (float)m_MinValue);
      m_MaxValue = vnl_math_max((float)inputIt.Get(), (float)m_MaxValue);
    }
    else
    {
      outputIt.Set(m_OutsideValue);
    }
  }
}
Ejemplo n.º 4
0
itk::Image<unsigned char, 3>::Pointer pdp::EMClassification::classify(itk::Image<float, 3>::Pointer img, itk::Image<unsigned char, 3>::Pointer mask)
{
	typedef itk::Vector< double, 1 > MeasurementVectorType;
	typedef itk::Image<unsigned char, 3> MaskType;
	typedef itk::Image<float, 3> ImageType;

	typedef itk::ImageRegionConstIterator< ImageType > ImageIteratorType;
	ImageIteratorType imgIt(img, img->GetLargestPossibleRegion());

	typedef itk::ImageRegionConstIterator< MaskType> MaskIteratorType;
	MaskIteratorType maskIt( mask, mask->GetLargestPossibleRegion());

	MaskType::Pointer correctImage = MaskType::New();
	correctImage->CopyInformation(mask);
	MaskType::RegionType outputRegion = mask->GetLargestPossibleRegion();
	correctImage->SetRegions( outputRegion );
	correctImage->Allocate();
	typedef itk::ImageRegionIterator<MaskType> IteratorType;
	IteratorType outputIt( correctImage, outputRegion);

	MeasurementVectorType mv;
	for ( imgIt.GoToBegin(), maskIt.GoToBegin(), outputIt.GoToBegin(); !maskIt.IsAtEnd(); ++maskIt, ++imgIt, ++outputIt)
	{

		if (maskIt.Get() == 255)
		{
			mv[0] = imgIt.Get();
			if (genLabel(mv) == 3)
			{
				outputIt.Set(255);
			}
		}
	}

	return correctImage;
}
Ejemplo n.º 5
0
void mitk::_InternalComputeClippedImage(itk::Image<TPixel, VImageDimension>* inputItkImage, mitk::GeometryClipImageFilter* geometryClipper, const mitk::Geometry2D* clippingGeometry2D)
{
  typedef itk::Image<TPixel, VImageDimension> ItkInputImageType;
  typedef itk::Image<TPixel, VImageDimension> ItkOutputImageType;

  typedef itk::ImageRegionConstIteratorWithIndex< ItkInputImageType > ItkInputImageIteratorType;
  typedef itk::ImageRegionIteratorWithIndex< ItkOutputImageType > ItkOutputImageIteratorType;

  typename mitk::ImageToItk<ItkOutputImageType>::Pointer outputimagetoitk = mitk::ImageToItk<ItkOutputImageType>::New();
  outputimagetoitk->SetInput(geometryClipper->m_OutputTimeSelector->GetOutput());
  outputimagetoitk->Update();
  typename ItkOutputImageType::Pointer outputItkImage = outputimagetoitk->GetOutput();

  // create the iterators
  typename ItkInputImageType::RegionType inputRegionOfInterest = inputItkImage->GetLargestPossibleRegion();
  ItkInputImageIteratorType  inputIt( inputItkImage, inputRegionOfInterest );
  ItkOutputImageIteratorType outputIt( outputItkImage, inputRegionOfInterest );

  typename ItkOutputImageType::PixelType outsideValue;
  if(geometryClipper->m_AutoOutsideValue)
    outsideValue = itk::NumericTraits<typename ItkOutputImageType::PixelType>::min();
  else
    outsideValue = (typename ItkOutputImageType::PixelType) geometryClipper->m_OutsideValue;

  mitk::Geometry3D* inputGeometry = geometryClipper->m_InputTimeSelector->GetOutput()->GetGeometry();
  typedef itk::Index<VImageDimension> IndexType;
  Point3D indexPt; indexPt.Fill(0);
  int i, dim=IndexType::GetIndexDimension();
  Point3D pointInMM;
  bool above = geometryClipper->m_ClipPartAboveGeometry;
  bool labelBothSides = geometryClipper->GetLabelBothSides();

  if (geometryClipper->GetAutoOrientLabels())
  {
    Point3D leftMostPoint;
    leftMostPoint.Fill( std::numeric_limits<float>::min() / 2.0 );
    if(clippingGeometry2D->IsAbove(pointInMM) != above)
      {
      // invert meaning of above --> left is always the "above" side
      above = !above;
    MITK_INFO << leftMostPoint << " is BELOW geometry. Inverting meaning of above" << std::endl;
    }
    else
    MITK_INFO << leftMostPoint << " is above geometry" << std::endl;
  }

  typename ItkOutputImageType::PixelType aboveLabel = (typename ItkOutputImageType::PixelType)geometryClipper->GetAboveGeometryLabel();
  typename ItkOutputImageType::PixelType belowLabel = (typename ItkOutputImageType::PixelType)geometryClipper->GetBelowGeometryLabel();

  for ( inputIt.GoToBegin(), outputIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt, ++outputIt)
  {
    if((typename ItkOutputImageType::PixelType)inputIt.Get() == outsideValue)
    {
      outputIt.Set(outsideValue);
    }
    else
    {
      for(i=0;i<dim;++i)
        indexPt[i]=(mitk::ScalarType)inputIt.GetIndex()[i];
      inputGeometry->IndexToWorld(indexPt, pointInMM);
      if(clippingGeometry2D->IsAbove(pointInMM) == above)
      {
        if ( labelBothSides )
          outputIt.Set( aboveLabel );
        else
          outputIt.Set( outsideValue );
      }
      else
      {
        if ( labelBothSides)
          outputIt.Set( belowLabel );
        else
          outputIt.Set( inputIt.Get() );
      }
    }
  }
}
Ejemplo n.º 6
0
void InputOutputPatchEditor::fillMappingTree()
{
    /* Disable check state change tracking when the tree is filled */
    disconnect(m_mapTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
               this, SLOT(slotMapItemChanged(QTreeWidgetItem*, int)));

    m_mapTree->clear();

    /* Go through available input plugins and create tree nodes. */
    QStringListIterator inputIt(m_inputMap->pluginNames());
    while (inputIt.hasNext() == true)
    {
        quint32 i = 0;
        QString pluginName = inputIt.next();
        QStringListIterator iit(m_inputMap->pluginInputs(pluginName));
        while (iit.hasNext() == true)
        {
            QTreeWidgetItem* pitem = new QTreeWidgetItem(m_mapTree);
            pitem->setText(KMapColumnPluginName, pluginName);
            pitem->setText(KMapColumnDeviceName, iit.next());
            pitem->setFlags(pitem->flags() | Qt::ItemIsUserCheckable);
            if (m_currentInputPluginName == pluginName && m_currentInput == i)
                pitem->setCheckState(KMapColumnHasInput, Qt::Checked);
            else
                pitem->setCheckState(KMapColumnHasInput, Qt::Unchecked);
            pitem->setTextAlignment(KMapColumnHasInput, Qt::AlignHCenter);
            pitem->setText(KMapColumnInputLine, QString("%1").arg(i));
            pitem->setText(KMapColumnOutputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
            i++;
        }

        if (i == 0)
        {
            QTreeWidgetItem* pitem = new QTreeWidgetItem(m_mapTree);
            pitem->setText(KMapColumnPluginName, pluginName);
            pitem->setText(KMapColumnDeviceName, KInputNone);
            pitem->setText(KMapColumnInputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
            pitem->setText(KMapColumnOutputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
        }
    }
    /* Go through available output plugins and create/update tree nodes. */
    QStringListIterator outputIt(m_outputMap->pluginNames());
    while (outputIt.hasNext() == true)
    {
        QString pluginName = outputIt.next();
        quint32 i = 0;

        QTreeWidgetItem *item = itemLookup(pluginName, "");
        /* 1st case: Add new plugin */
        if (item == NULL)
        {
            QStringListIterator iit(m_outputMap->pluginOutputs(pluginName));
            while (iit.hasNext() == true)
            {
                /* Output capable device */
                QString devName = iit.next();
                QTreeWidgetItem* pitem = new QTreeWidgetItem(m_mapTree);
                pitem->setText(KMapColumnPluginName, pluginName);
                pitem->setText(KMapColumnDeviceName, devName);
                pitem->setFlags(pitem->flags() | Qt::ItemIsUserCheckable);
                if (m_currentOutputPluginName == pluginName && m_currentOutput == i)
                    pitem->setCheckState(KMapColumnHasOutput, Qt::Checked);
                else
                    pitem->setCheckState(KMapColumnHasOutput, Qt::Unchecked);
                pitem->setText(KMapColumnOutputLine, QString("%1").arg(i));
                pitem->setText(KMapColumnInputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
                /* If a device has an output, it means it can send feedbacks */
                if (pluginName == "MIDI")
                {
                    if (m_currentFeedbackPluginName == pluginName && m_currentFeedback == i)
                        pitem->setCheckState(KMapColumnHasFeedback, Qt::Checked);
                    else
                        pitem->setCheckState(KMapColumnHasFeedback, Qt::Unchecked);
                }
                i++;
            }
            if (i == 0)
            {
                /* Device not available: No input and no output */
                QTreeWidgetItem* pitem = new QTreeWidgetItem(m_mapTree);
                pitem->setText(KMapColumnPluginName, pluginName);
                pitem->setText(KMapColumnDeviceName, KInputNone);
                pitem->setText(KMapColumnOutputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
                pitem->setText(KMapColumnInputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
            }
        }
        else
        {
            QStringListIterator iit(m_outputMap->pluginOutputs(pluginName));
            while (iit.hasNext() == true)
            {
                QString devName = iit.next();
                QTreeWidgetItem *item = itemLookup(pluginName, devName);
                /* 2nd case: add new output-only device to an existing plugin */
                if (item == NULL)
                {
                    item = new QTreeWidgetItem(m_mapTree);
                    item->setText(KMapColumnPluginName, pluginName);
                    item->setText(KMapColumnDeviceName, devName);
                    item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
                    if (m_currentOutputPluginName == pluginName && m_currentOutput == i)
                        item->setCheckState(KMapColumnHasOutput, Qt::Checked);
                    else
                        item->setCheckState(KMapColumnHasOutput, Qt::Unchecked);

                    item->setText(KMapColumnOutputLine, QString("%1").arg(i));
                    item->setText(KMapColumnInputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
                }
                else
                {
                    /* 3rd case: add an output line to an existing device with an input line */
                    item->setText(KMapColumnDeviceName, devName);
                    if (m_currentOutputPluginName == pluginName && m_currentOutput == i)
                        item->setCheckState(KMapColumnHasOutput, Qt::Checked);
                    else
                        item->setCheckState(KMapColumnHasOutput, Qt::Unchecked);
                    item->setText(KMapColumnOutputLine, QString("%1").arg(i));
                }
                /* If a device has both input and output, it means it can send feedbacks */
                if (pluginName == "MIDI")
                {
                    if (m_currentFeedbackPluginName == pluginName && m_currentFeedback == i)
                        item->setCheckState(KMapColumnHasFeedback, Qt::Checked);
                    else
                        item->setCheckState(KMapColumnHasFeedback, Qt::Unchecked);
                }
                i++;
            }
        }
    }

    /* Enable check state change tracking after the tree has been filled */
    connect(m_mapTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
            this, SLOT(slotMapItemChanged(QTreeWidgetItem*, int)));
}
Ejemplo n.º 7
0
void vtkApplyLookupTableOnScalarsCTF(vtkMitkLevelWindowFilter *self,
                                     vtkImageData *inData,
                                     vtkImageData *outData,
                                     int outExt[6],
                                     vtkFloatingPointType* clippingBounds,
                                     T *)
{
    vtkImageIterator<T> inputIt(inData, outExt);
    vtkImageIterator<unsigned char> outputIt(outData, outExt);
    vtkColorTransferFunction* lookupTable =  dynamic_cast<vtkColorTransferFunction*>(self->GetLookupTable());

    int y = outExt[2];

    // Loop through ouput pixels
    while (!outputIt.IsAtEnd())
    {
        unsigned char* outputSI = outputIt.BeginSpan();
        unsigned char* outputSIEnd = outputIt.EndSpan();

        // do we iterate over the inner vertical clipping bounds
        if( y >= clippingBounds[2] && y < clippingBounds[3] )
        {
            T* inputSI = inputIt.BeginSpan();

            int x= outExt[0];

            while (outputSI != outputSIEnd)
            {
                // is this pixel within horizontal clipping bounds
                if ( x >= clippingBounds[0] && x < clippingBounds[1])
                {
                    // fetching original value
                    double grayValue = static_cast<double>(*inputSI);

                    // applying directly colortransferfunction
                    // because vtkColorTransferFunction::MapValue is not threadsafe
                    double rgb[3];
                    lookupTable->GetColor( grayValue, rgb );

                    outputSI[0] = static_cast<unsigned char>(255.0*rgb[0] + 0.5);
                    outputSI[1] = static_cast<unsigned char>(255.0*rgb[1] + 0.5);
                    outputSI[2] = static_cast<unsigned char>(255.0*rgb[2] + 0.5);
                    outputSI[3] = 255;
                }
                else
                {
                    // outer horizontal clipping bounds - write a transparent RGBA pixel as a single int
                    *reinterpret_cast<int*>(outputSI) = 0;
                }

                inputSI++;
                outputSI+=4;
                x++;
            }

        }
        else
        {
            // outer vertical clipping bounds - write a transparent RGBA line as ints
            while (outputSI != outputSIEnd)
            {
                *reinterpret_cast<int*>(outputSI) = 0;
                outputSI+=4;
            }
        }

        inputIt.NextSpan();
        outputIt.NextSpan();
        y++;
    }
}
Ejemplo n.º 8
0
void vtkApplyLookupTableOnScalars(vtkMitkLevelWindowFilter *self,
                                  vtkImageData *inData,
                                  vtkImageData *outData,
                                  int outExt[6],
                                  vtkFloatingPointType* clippingBounds,
                                  T *)
{
    vtkImageIterator<T> inputIt(inData, outExt);
    vtkImageIterator<unsigned char> outputIt(outData, outExt);
    vtkScalarsToColors* lookupTable = self->GetLookupTable();

    int y = outExt[2];

    // Loop through ouput pixels
    while (!outputIt.IsAtEnd())
    {
        unsigned char* outputSI = outputIt.BeginSpan();
        unsigned char* outputSIEnd = outputIt.EndSpan();

        // do we iterate over the inner vertical clipping bounds
        if( y >= clippingBounds[2] && y < clippingBounds[3] )
        {
            T* inputSI = inputIt.BeginSpan();

            int x= outExt[0];

            while (outputSI != outputSIEnd)
            {
                // is this pixel within horizontal clipping bounds
                if ( x >= clippingBounds[0] && x < clippingBounds[1])
                {
                    // fetching original value
                    double grayValue = static_cast<double>(*inputSI);
                    // applying lookuptable - copy the 4 (RGBA) chars as a single int
                    *reinterpret_cast<int*>(outputSI) = *reinterpret_cast<int *>(lookupTable->MapValue( grayValue ));
                }
                else
                {
                    // outer horizontal clipping bounds - write a transparent RGBA pixel as a single int
                    *reinterpret_cast<int*>(outputSI) = 0;
                }

                inputSI++;
                outputSI+=4;
                x++;
            }

        }
        else
        {
            // outer vertical clipping bounds - write a transparent RGBA line as ints
            while (outputSI != outputSIEnd)
            {
                *reinterpret_cast<int*>(outputSI) = 0;
                outputSI+=4;
            }
        }

        inputIt.NextSpan();
        outputIt.NextSpan();
        y++;
    }
}
Ejemplo n.º 9
0
void vtkApplyLookupTableOnRGBA(vtkMitkLevelWindowFilter* self,
                               vtkImageData* inData,
                               vtkImageData* outData,
                               int outExt[6],
                               vtkFloatingPointType* clippingBounds,
                               T*)
{
    vtkImageIterator<T> inputIt(inData, outExt);
    vtkImageIterator<T> outputIt(outData, outExt);
    vtkLookupTable* lookupTable;
    const int maxC = inData->GetNumberOfScalarComponents();

    double tableRange[2];

    lookupTable = dynamic_cast<vtkLookupTable*>(self->GetLookupTable());

    lookupTable->GetTableRange(tableRange);

    //parameters for RGB level window
    double scale = (tableRange[1] -tableRange[0] > 0 ? 255.0 / (tableRange[1] - tableRange[0]) : 0.0);
    double bias = tableRange[0] * scale;

    //parameters for opaque level window
    double scaleOpac = (self->GetMaxOpacity() -self->GetMinOpacity() > 0 ? 255.0 / (self->GetMaxOpacity() - self->GetMinOpacity()) : 0.0);
    double biasOpac = self->GetMinOpacity() * scaleOpac;

    int y = outExt[2];

    // Loop through ouput pixels
    while (!outputIt.IsAtEnd())
    {
        T* inputSI = inputIt.BeginSpan();
        T* outputSI = outputIt.BeginSpan();
        T* outputSIEnd = outputIt.EndSpan();

        if( y >= clippingBounds[2] && y < clippingBounds[3] )
        {
            int x = outExt[0];

            while (outputSI != outputSIEnd)
            {
                if ( x >= clippingBounds[0] && x < clippingBounds[1])
                {
                    double rgb[3], alpha, hsi[3];

                    // level/window mechanism for intensity in HSI space
                    rgb[0] = static_cast<double>(*inputSI);
                    inputSI++;
                    rgb[1] = static_cast<double>(*inputSI);
                    inputSI++;
                    rgb[2] = static_cast<double>(*inputSI);
                    inputSI++;

                    RGBtoHSI<double>(rgb,hsi);
                    hsi[2] = hsi[2] * 255.0 * scale - bias;
                    hsi[2] = (hsi[2] > 255.0 ? 255 : (hsi[2] < 0.0 ? 0 : hsi[2]));
                    hsi[2] /= 255.0;
                    HSItoRGB<double>(hsi,rgb);

                    *outputSI = static_cast<T>(rgb[0]);
                    outputSI++;
                    *outputSI = static_cast<T>(rgb[1]);
                    outputSI++;
                    *outputSI = static_cast<T>(rgb[2]);
                    outputSI++;

                    unsigned char finalAlpha = 255;

                    //RGBA case
                    if(maxC >= 4)
                    {
                        // level/window mechanism for opacity
                        alpha = static_cast<double>(*inputSI);
                        inputSI++;
                        alpha = alpha * scaleOpac - biasOpac;
                        if(alpha > 255.0)
                        {
                            alpha = 255.0;
                        }
                        else if(alpha < 0.0)
                        {
                            alpha = 0.0;
                        }
                        finalAlpha = static_cast<unsigned char>(alpha);

                        for( int c = 4; c < maxC; c++ )
                            inputSI++;

                    }

                    *outputSI = static_cast<T>(finalAlpha);
                    outputSI++;
                }
                else
                {
                    inputSI+=maxC;
                    *outputSI = 0;
                    outputSI++;
                    *outputSI = 0;
                    outputSI++;
                    *outputSI = 0;
                    outputSI++;
                    *outputSI = 0;
                    outputSI++;
                }

                x++;
            }
        }
        else
        {
            while (outputSI != outputSIEnd)
            {
                *outputSI = 0;
                outputSI++;
                *outputSI = 0;
                outputSI++;
                *outputSI = 0;
                outputSI++;
                *outputSI = 0;
                outputSI++;
            }
        }
        inputIt.NextSpan();
        outputIt.NextSpan();
        y++;
    }
}
  void HeightFieldSurfaceClipImageFilter::_InternalComputeClippedImage(
    itk::Image<TPixel, VImageDimension> *inputItkImage,
    HeightFieldSurfaceClipImageFilter *clipImageFilter,
    vtkPolyData *clippingPolyData,
    AffineTransform3D *imageToPlaneTransform)
  {
    typedef itk::Image<TPixel, VImageDimension> ItkInputImageType;
    typedef itk::Image<TPixel, VImageDimension> ItkOutputImageType;

    typedef itk::ImageSliceConstIteratorWithIndex<ItkInputImageType> ItkInputImageIteratorType;
    typedef itk::ImageRegionIteratorWithIndex<ItkOutputImageType> ItkOutputImageIteratorType;

    typename ImageToItk<ItkOutputImageType>::Pointer outputimagetoitk = ImageToItk<ItkOutputImageType>::New();
    outputimagetoitk->SetInput(clipImageFilter->m_OutputTimeSelector->GetOutput());
    outputimagetoitk->Update();

    typename ItkOutputImageType::Pointer outputItkImage = outputimagetoitk->GetOutput();
    std::vector<double> test;

    // create the iterators
    typename ItkInputImageType::RegionType inputRegionOfInterest = inputItkImage->GetLargestPossibleRegion();
    ItkInputImageIteratorType inputIt(inputItkImage, inputRegionOfInterest);
    ItkOutputImageIteratorType outputIt(outputItkImage, inputRegionOfInterest);

    // Get bounds of clipping data
    clippingPolyData->ComputeBounds();
    double *bounds = clippingPolyData->GetBounds();

    double xWidth = bounds[1] - bounds[0];
    double yWidth = bounds[3] - bounds[2];

    // Create vtkCellLocator for clipping poly data
    vtkCellLocator *cellLocator = vtkCellLocator::New();
    cellLocator->SetDataSet(clippingPolyData);
    cellLocator->CacheCellBoundsOn();
    cellLocator->AutomaticOn();
    cellLocator->BuildLocator();

    // Allocate memory for 2D image to hold the height field generated by
    // projecting the clipping data onto the plane
    auto heightField = new double[m_HeightFieldResolutionX * m_HeightFieldResolutionY];

    // Walk through height field and for each entry calculate height of the
    // clipping poly data at this point by means of vtkCellLocator. The
    // clipping data x/y bounds are used for converting from poly data space to
    // image (height-field) space.
    MITK_INFO << "Calculating Height Field..." << std::endl;
    for (unsigned int y = 0; y < m_HeightFieldResolutionY; ++y)
    {
      for (unsigned int x = 0; x < m_HeightFieldResolutionX; ++x)
      {
        double p0[3], p1[3], surfacePoint[3], pcoords[3];
        p0[0] = bounds[0] + xWidth * x / (double)m_HeightFieldResolutionX;
        p0[1] = bounds[2] + yWidth * y / (double)m_HeightFieldResolutionY;
        p0[2] = -m_MaxHeight;

        p1[0] = p0[0];
        p1[1] = p0[1];
        p1[2] = m_MaxHeight;

        double t, distance;
        int subId;
        if (cellLocator->IntersectWithLine(p0, p1, 0.1, t, surfacePoint, pcoords, subId))
        {
          distance = (2.0 * t - 1.0) * m_MaxHeight;
        }
        else
        {
          distance = -65536.0;
        }
        heightField[y * m_HeightFieldResolutionX + x] = distance;
        itk::Image<double, 2>::IndexType index;
        index[0] = x;
        index[1] = y;
      }
    }

    // Walk through entire input image and for each point determine its distance
    // from the x/y plane.
    MITK_INFO << "Performing clipping..." << std::endl;

    TPixel factor = static_cast<TPixel>(clipImageFilter->m_MultiplicationFactor);
    TPixel clippingConstant = clipImageFilter->m_ClippingConstant;

    inputIt.SetFirstDirection(0);
    inputIt.SetSecondDirection(1);
    // through all slices
    for (inputIt.GoToBegin(), outputIt.GoToBegin(); !inputIt.IsAtEnd(); inputIt.NextSlice())
    {
      // through all lines of a slice
      for (; !inputIt.IsAtEndOfSlice(); inputIt.NextLine())
      {
        // Transform the start(line) point from the image to the plane
        Point3D imageP0, planeP0;
        imageP0[0] = inputIt.GetIndex()[0];
        imageP0[1] = inputIt.GetIndex()[1];
        imageP0[2] = inputIt.GetIndex()[2];
        planeP0 = imageToPlaneTransform->TransformPoint(imageP0);

        // Transform the end point (line) from the image to the plane
        Point3D imageP1, planeP1;
        imageP1[0] = imageP0[0] + inputRegionOfInterest.GetSize(0);
        imageP1[1] = imageP0[1];
        imageP1[2] = imageP0[2];
        planeP1 = imageToPlaneTransform->TransformPoint(imageP1);

        // calculate the step size (if the plane is rotate, you go "crossway" through the image)
        Vector3D step = (planeP1 - planeP0) / (double)inputRegionOfInterest.GetSize(0);

        // over all pixel
        for (; !inputIt.IsAtEndOfLine(); ++inputIt, ++outputIt, planeP0 += step)
        {
          // Only ConstantMode: if image pixel value == constant mode value-->set output pixel value directly
          if ((clipImageFilter->m_ClippingMode == CLIPPING_MODE_CONSTANT) &&
              ((TPixel)inputIt.Get() == clippingConstant))
          {
            outputIt.Set(clippingConstant);
          }

          else
          {
            int x0 = (int)((double)(m_HeightFieldResolutionX) * (planeP0[0] - bounds[0]) / xWidth);
            int y0 = (int)((double)(m_HeightFieldResolutionY) * (planeP0[1] - bounds[2]) / yWidth);

            bool clip;

            // if the current point is outside of the plane region (RegionOfInterest)-->clip the pixel allways
            if ((x0 < 0) || (x0 >= (int)m_HeightFieldResolutionX) || (y0 < 0) || (y0 >= (int)m_HeightFieldResolutionY))
            {
              clip = true;
            }

            else
            {
              // Calculate bilinearly interpolated height field value at plane point
              int x1 = x0 + 1;
              int y1 = y0 + 1;
              if (x1 >= (int)m_HeightFieldResolutionX)
              {
                x1 = x0;
              }
              if (y1 >= (int)m_HeightFieldResolutionY)
              {
                y1 = y0;
              }

              // Get the neighbour points for the interpolation
              ScalarType q00, q01, q10, q11;
              q00 = heightField[y0 * m_HeightFieldResolutionX + x0];
              q01 = heightField[y0 * m_HeightFieldResolutionX + x1];
              q10 = heightField[y1 * m_HeightFieldResolutionX + x0];
              q11 = heightField[y1 * m_HeightFieldResolutionX + x1];

              double p00 = ((double)(m_HeightFieldResolutionX) * (planeP0[0] - bounds[0]) / xWidth);
              double p01 = ((double)(m_HeightFieldResolutionY) * (planeP0[1] - bounds[2]) / yWidth);

              ScalarType q =
                q00 * ((double)x1 - p00) * ((double)y1 - p01) + q01 * (p00 - (double)x0) * ((double)y1 - p01) +
                q10 * ((double)x1 - p00) * (p01 - (double)y0) + q11 * (p00 - (double)x0) * (p01 - (double)y0);

              if (q - planeP0[2] < 0)
              {
                clip = true;
              }
              else
              {
                clip = false;
              }
            }

            // different modes: differnt values for the clipped pixel
            if (clip)
            {
              if (clipImageFilter->m_ClippingMode == CLIPPING_MODE_CONSTANT)
              {
                outputIt.Set(clipImageFilter->m_ClippingConstant);
              }
              else if (clipImageFilter->m_ClippingMode == CLIPPING_MODE_MULTIPLYBYFACTOR)
              {
                outputIt.Set(inputIt.Get() * factor);
              }
              else if (clipImageFilter->m_ClippingMode == CLIPPING_MODE_MULTIPLANE)
              {
                if (inputIt.Get() != 0)
                  outputIt.Set(inputIt.Get() + m_MultiPlaneValue);
                else
                  outputIt.Set(inputIt.Get());
              }
            }
            // the non-clipped pixel keeps his value
            else
            {
              outputIt.Set(inputIt.Get());
            }
          }
        }
      }
    }

    MITK_INFO << "DONE!" << std::endl;

    // Clean-up
    cellLocator->Delete();
  }
Ejemplo n.º 11
0
void TrackingKymoView::GenerateImages()
{
	float col[3]={1.0,1.0,1.0};
	m_vtkim = vtkSmartPointer<vtkImageData>::New();
//	InputImageType::SizeType imsize = m_model->getRawImagePointer(0)->GetLargestPossibleRegion().GetSize();
	unsigned short xsize = (my4DImg->GetImageInfo()->numColumns);
	unsigned short ysize = (my4DImg->GetImageInfo()->numRows);
	unsigned short tsize = (my4DImg->GetImageInfo()->numTSlices);

	m_vtkim->SetExtent(0,xsize-1,0,ysize-1,0,tsize-1);
	m_vtkim->SetScalarTypeToUnsignedChar();
	m_vtkim->AllocateScalars();
	m_vtkim->SetSpacing(1.0,1.0,5.0);

	//Loop Constants:
	unsigned short xy = xsize*ysize;
	ftk::Image::PtrMode mode;
	mode = static_cast<ftk::Image::PtrMode>(0); 

/*	for(unsigned short t=0; t< tsize; t++)
	{
		Input2DImageType::Pointer my2DImage = getProjection(my4DImg->GetItkPtr<InputPixelType>(t,0,mode));
		memcpy(static_cast<unsigned char*>(m_vtkim->GetScalarPointer())+xsize*ysize*t,my2DImage->GetBufferPointer(),sizeof(unsigned char)*xsize*ysize);
	}*/

	Input2DImageType::Pointer my2DImage = Input2DImageType::New();
	Input2DImageType::RegionType region;
	Input2DImageType::SizeType size;
	Input2DImageType::IndexType index;
	index[0]=0;
	index[1]=0;
	size[0] = xsize;
	size[1] = ysize;
	region.SetSize(size);
	region.SetIndex(index);
	my2DImage->SetRegions(region);
	my2DImage->Allocate();

	for(unsigned short t=0; t< tsize; t++)
	{
		SliceIteratorType inputIt(my4DImg->GetItkPtr<InputPixelType>(t,0,mode),my4DImg->GetItkPtr<InputPixelType>(t,0,mode)->GetLargestPossibleRegion());
		LinearIteratorType outputIt(my2DImage,my2DImage->GetLargestPossibleRegion());

		inputIt.SetFirstDirection(0);
		inputIt.SetSecondDirection(1);
		outputIt.SetDirection(0);
		outputIt.GoToBegin();
		while ( ! outputIt.IsAtEnd() )
		{
			while ( ! outputIt.IsAtEndOfLine() )
			{
				outputIt.Set( itk::NumericTraits<unsigned short>::NonpositiveMin() );
				++outputIt;
			}
			outputIt.NextLine();
		}

		inputIt.GoToBegin();
		outputIt.GoToBegin();
		while( !inputIt.IsAtEnd() )
		{
			while ( !inputIt.IsAtEndOfSlice() )
			{
				while ( !inputIt.IsAtEndOfLine() )
				{
					outputIt.Set( MAX( outputIt.Get(), inputIt.Get() ));
					++inputIt;
					++outputIt;
				}
				outputIt.NextLine();
				inputIt.NextLine();
			}
			outputIt.GoToBegin();
			inputIt.NextSlice();
		}

		memcpy(static_cast<unsigned char*>(m_vtkim->GetScalarPointer())+xsize*ysize*t,my2DImage->GetBufferPointer(),sizeof(unsigned char)*xsize*ysize);
	}
	
	m_vtkvolume = getOneVTKVolume(m_vtkim,col);
	//m_vtkvolume->Print(std::cout);
	m_vtkrenderer->AddVolume(m_vtkvolume);
	m_vtkrenderer->ResetCamera(m_vtkim->GetBounds());

}
Ejemplo n.º 12
0
void CAxialFor3DView::cropImage(ImagePointer source , ImagePointer target,int nStartSlice, int nEndSlice)
{
	const unsigned int Dimension = 3;

	typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;
	typedef itk::ImageRegionIterator< ImageType>       IteratorType;

	ImageType::RegionType inputRegion;

	ImageType::RegionType::IndexType inputStart;
	ImageType::RegionType::SizeType  size;

	inputStart[0] = 0;//174 m_nCropStart[0]
	inputStart[1] = 0;//160 m_nCropStart[1]
	inputStart[2] = nStartSlice;

	size[0]  = m_nWidth;//193 m_nCropSize[0]
	size[1]  = m_nHeight;//193 m_nCropSize[1]
	size[2]  = nEndSlice-nStartSlice+1;//350 746

	inputRegion.SetSize( size );
	inputRegion.SetIndex( inputStart );

	ImageType::RegionType outputRegion;

	ImageType::RegionType::IndexType outputStart;

	outputStart[0] = 0;
	outputStart[1] = 0;
	outputStart[2] = 0;

	outputRegion.SetSize( size );
	outputRegion.SetIndex( outputStart );
	
	target->SetRegions( outputRegion );
	const ImageType::SpacingType& spacing = source->GetSpacing();
	const ImageType::PointType& inputOrigin = source->GetOrigin();
	double   outputOrigin[ Dimension ];

	for(unsigned int i=0; i< Dimension; i++)
	{
		outputOrigin[i] = inputOrigin[i] + spacing[i] * inputStart[i];
	}

	target->SetSpacing( spacing );
	target->SetOrigin(  outputOrigin );
	target->Allocate();

	ConstIteratorType inputIt(   source, inputRegion  );
	IteratorType      outputIt(  target, outputRegion );

	for ( inputIt.GoToBegin(), outputIt.GoToBegin(); !inputIt.IsAtEnd();
		++inputIt, ++outputIt)
	{
		outputIt.Set(  inputIt.Get()  );
	}	

	itkVTKResampleExporter->SetInput(target);
	VTKResampleImporter->SetDataOrigin(0,0,0);
	itkVTKResampleExporter->Update();

	greyPadder->SetInput(VTKResampleImporter->GetOutput());

	greyPadder->SetOutputWholeExtent(0,m_nWidth,0,m_nHeight,0,0);
	greyPadder->SetConstant(0);
	m_nSliceSum=nEndSlice-nStartSlice;

	m_bCropImage=true;
	VTKImporter->Delete();
	source->ReleaseData();
	//seriesReader->Delete();
	//itkVTKExporter->RemoveInput();
	//itkVTKExporter->RemoveOutput();
}