void NonGradient::optimize_vertex_positions(PatchData &pd, 
                                            MsqError &err)
{
  MSQ_FUNCTION_TIMER( "NonGradient::optimize_vertex_positions" );
  int numRow = getDimension();
  int numCol = numRow+1;  
  std::vector<double> height(numCol); 

  for(int col = 0; col < numCol; col++)
  {
    height[col] =  evaluate(&simplex[col*numRow], pd, err);//  eval patch stuff
  }
  if(mNonGradDebug > 0)
  {
    printSimplex( simplex, height );
  }

  // standardization
  TerminationCriterion* term_crit=get_inner_termination_criterion();
  int maxNumEval = getMaxNumEval();
  double threshold = getThreshold();
//  double ftol = getTolerance();
  int ilo = 0;  //height[ilo]<=...
  int inhi = 0; //...<=height[inhi]<=
  int ihi = 0;  //<=height[ihi] 
//  double rtol = 2.*ftol;
  double ysave;
  double ytry;
  bool afterEvaluation = false;
  std::vector<double> rowSum(numRow);
  getRowSum( numRow, numCol, simplex, rowSum);
  while( !( term_crit->terminate() ) )
  {

    if(mNonGradDebug > 0)
    {
      printSimplex( simplex, height );
    }
    //std::cout << "rtol " << rtol << " ftol " << ftol << " MesquiteIter " << term_crit->get_iteration_count() << " Done " << term_crit->terminate() << std::endl;

    if( afterEvaluation )   
    {
      // reflect highPt through opposite face
      // height[0] may vanish
/*
      if( !testRowSum( numRow, numCol, &simplex[0], &rowSum[0]) )
      {
        // Before uncommenting here and ... 
        //MSQ_SETERR(err)("Internal check sum test A failed", MsqError::INTERNAL_ERROR);
        //MSQ_ERRRTN(err);
      }
*/
      ytry=amotry(simplex,height,&rowSum[0],ihi,-1.0, pd, err);
/*
      if( !testRowSum( numRow, numCol, &simplex[0], &rowSum[0]) )
      {
         // ... here, determine a maxVal majorizing the previous as well as the current simplex.
         //MSQ_SETERR(err)("Internal check sum test B failed", MsqError::INTERNAL_ERROR);
         //MSQ_ERRRTN(err);
      }   
*/
  
/*
      if( height[0] == 0.)
      {
         MSQ_SETERR(err)("(B) Zero objective function value", MsqError::INTERNAL_ERROR);
         exit(-1);
      }
*/
      if (ytry <= height[ilo])   
      {
        ytry=amotry(simplex,height,&rowSum[0],ihi,-2.0,pd,err);
        if( mNonGradDebug >= 3 ) 
        {      
         std::cout << "Reflect and Expand from highPt " << ytry << std::endl;
        }      
        //MSQ_PRINT(3)("Reflect and Expand from highPt : %e\n",ytry);
      }
      else 
      {
        if (ytry >= height[inhi]) 
        {
          ysave=height[ihi]; // Contract along highPt
          ytry=amotry(simplex,height,&rowSum[0],ihi,0.5,pd,err);
          if (ytry >= ysave)
          { // contract all directions toward lowPt
            for (int col=0;col<numCol;col++)
            {
              if (col != ilo)
              {
                for (int row=0;row<numRow;row++)
                {
                  rowSum[row]=0.5*(simplex[row+col*numRow]+simplex[row+ilo*numRow]);
                  simplex[row+col*numRow]=rowSum[row];
                }
                height[col] = evaluate(&rowSum[0], pd, err); 
                if( mNonGradDebug >= 3 ) 
                {      
                  std::cout << "Contract all directions toward lowPt value( " << col << " ) = " << height[col] << " ilo = " << ilo << std::endl;
                }      
                //MSQ_PRINT(3)("Contract all directions toward lowPt value( %d ) = %e    ilo = %d\n", col, height[col], ilo);
              }
            }
          }
        }   
      } // ytri > h(ilo) 
    } // after evaluation
    ilo=1; // conditional operator or inline if 
    ihi = height[0] > height[1] ? (inhi=1,0) : (inhi=0,1);
    for (int col=0;col<numCol;col++)
    {
      if (height[col] <= height[ilo])
      {
        ilo=col;  // ilo := argmin height
      }
      if (height[col] > height[ihi])
      {
        inhi=ihi;
        ihi=col;
      } 
      else  // height[ihi] >= height[col]
        if (col != ihi && height[col] > height[inhi] ) inhi=col;
    }
//    rtol=2.0*fabs( height[ihi]-height[ilo] )/
//         ( fabs(height[ihi])+fabs(height[ilo])+threshold );
    afterEvaluation = true;
  } //  while not converged 

  // Always set to current best mesh.
  { 
    if( ilo != 0 )
    {
      double yTemp = height[0];
      height[0] = height[ilo]; // height dimension numCol
      height[ilo] = yTemp;
      for (int row=1;row<numRow;row++)
      { 
          yTemp = simplex[row];
          simplex[row] = simplex[row+ilo*numRow];
          simplex[row+ilo*numRow] = yTemp;
      }
    }
  }
  if( pd.num_free_vertices() > 1 )
  {
    MSQ_SETERR(err)("Only one free vertex per patch implemented", MsqError::NOT_IMPLEMENTED);
  }

  Vector3D newPoint( &simplex[0] ); 
  size_t vertexIndex = 0; // fix c.f. freeVertexIndex
  pd.set_vertex_coordinates( newPoint, vertexIndex, err ); 
  pd.snap_vertex_to_domain( vertexIndex, err );
  if( term_crit->terminate() )
  {
    if( mNonGradDebug >= 1 ) 
    {      
         std::cout << "Optimization Termination OptStatus: Max Iter Exceeded" << std::endl;
    }      
    //MSQ_PRINT(1)("Optimization Termination OptStatus: Max Iter Exceeded\n"); 
  }
}
예제 #2
0
void Joystick::setY(float y) {
    if ( (y > 0.0f && y < getThreshold()) || (y < 0.0f && y > getThreshold() * -1.0f) ) {
        y = 0.0f;
    }

    m_y = y;
}
예제 #3
0
void IrSensor::process(const double dt)
{
   BaseClass::process(dt);

   int numRecords = storedMessagesQueue.entries();
   if (numRecords > 0) {
      AngleOnlyTrackManager* tm = static_cast<AngleOnlyTrackManager*>(getTrackManager());
      if (tm != nullptr) {
         base::lock(storedMessagesLock);
         numRecords = storedMessagesQueue.entries();

         // Send on all messages EXCEPT those with signal below threshold and those merged
         // into another signal. Those will simply be ignored and unreferenced.

         for (int i=0; i < numRecords; i++) {
            IrQueryMsg* msg = storedMessagesQueue.get();
            if (msg->getQueryMergeStatus() != IrQueryMsg::MERGED_OUT) {
               if (msg->getSignalToNoiseRatio() > getThreshold())
                  tm->newReport(msg, msg->getSignalToNoiseRatio());
            }
            msg->unref();
         }
         base::unlock(storedMessagesLock);
      }
   }
}
예제 #4
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void Watershed::readFilterParameters(AbstractFilterParametersReader* reader, int index)
{
  reader->openFilterGroup(this, index);
  setSelectedCellArrayPath( reader->readDataArrayPath( "SelectedCellArrayPath", getSelectedCellArrayPath() ) );
  setFeatureIdsArrayName( reader->readString( "FeatureIdsArrayName", getFeatureIdsArrayName() ) );
  setThreshold( reader->readValue( "Threshold", getThreshold() ) );
  setLevel( reader->readValue( "Level", getLevel() ) );
  reader->closeFilterGroup();
}
예제 #5
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int Watershed::writeFilterParameters(AbstractFilterParametersWriter* writer, int index)
{
  writer->openFilterGroup(this, index);
  writer->writeValue( "SelectedCellArrayPath", getSelectedCellArrayPath() );
  writer->writeValue( "FeatureIdsArrayName", getFeatureIdsArrayName() );
  writer->writeValue( "Threshold", getThreshold() );
  writer->writeValue( "Level", getLevel() );
  writer->closeFilterGroup();
  return ++index; // we want to return the next index that was just written to
}
ossimRefPtr<ossimProperty> ossimCFARFilter::getProperty(const ossimString& name)const
{
   if(name == "Kernel")
   {
      ossimMatrixProperty* property = new ossimMatrixProperty(name);
      property->resize(5,5);
      for(ossim_int32 r = 0; r < 5; r++)
   	{
      	for(ossim_int32 c = 0; c < 5; c++)
      	{
      		(*property)(r,c) = theKernel[r][c];
      	}
   	}
   	/*
      (*property)(0,0) = theKernel[0][0];
      (*property)(1,0) = theKernel[1][0];
      (*property)(2,0) = theKernel[2][0];
      (*property)(3,0) = theKernel[3][0];
      (*property)(4,0) = theKernel[4][0];
      (*property)(0,1) = theKernel[0][1];
      (*property)(1,1) = theKernel[1][1];
      (*property)(2,1) = theKernel[2][1];
      (*property)(3,1) = theKernel[3][1];
      (*property)(4,1) = theKernel[4][1];
      (*property)(0,2) = theKernel[0][2];
      (*property)(1,2) = theKernel[1][2];
      (*property)(2,2) = theKernel[2][2];
      (*property)(3,2) = theKernel[3][2];
      (*property)(4,2) = theKernel[4][2];
      (*property)(0,3) = theKernel[0][3];
      (*property)(1,3) = theKernel[1][3];
      (*property)(2,3) = theKernel[2][3];
      (*property)(3,3) = theKernel[3][3];
      (*property)(4,3) = theKernel[4][3];
      (*property)(0,4) = theKernel[0][4];
      (*property)(1,4) = theKernel[1][4];
      (*property)(2,4) = theKernel[2][4];
      (*property)(3,4) = theKernel[3][4];
      (*property)(4,4) = theKernel[4][4];
      */
      property->setCacheRefreshBit();

      return property;
   }
   if(name == "threshold")
   {
   	 ossimNumericProperty* numeric = new ossimNumericProperty(name,
                                                               ossimString::toString(getThreshold()),
                                                               -10.0, 10.0);
      numeric->setNumericType(ossimNumericProperty::ossimNumericPropertyType_FLOAT64);
      numeric->setCacheRefreshBit();
      return numeric;
   }
   return ossimImageSourceFilter::getProperty(name);
}
예제 #7
0
bool XAGYLWheel::getSettingInfo()
{
    bool rc1 = getMaximumSpeed();
    bool rc2 = getJitter();
    bool rc3 = getThreshold();
    bool rc4 = true;

    if (firmwareVersion >= 3)
        rc4 = getPulseWidth();

    return (rc1 && rc2 && rc3 && rc4);
}
예제 #8
0
 void set( T new_value )
 {
   if( value == -1 )
     value = new_value;
   else {
     T delta = new_value - value;
     const T threshold = getThreshold( (new_value + value)/2 );
     if( delta > threshold ) delta = threshold;
     else if( delta < -threshold ) delta = -threshold;
     value += delta;
   }
 }
struct bed3 *regionsOverThreshold(struct genoGraph *gg)
/* Get list of regions over threshold */
{
/* Get list of regions. */
if (gg == NULL)
    errAbort("Please go back and select a graph.");
double threshold = getThreshold();
struct bed3 *bedList = chromGraphBinToBed3(gg->binFileName, threshold);
if (bedList == NULL)
    errAbort("No regions over %g, please go back and set a lower threshold",
    	threshold);
int pad = regionPad();
addPadToBed3(bedList, -pad, pad);
return bedList;
}
예제 #10
0
ThresholdResolution::ThresholdPolicy*
    MfgThresholdMgr::getThresholdP(uint32_t i_thrName)
{
    uint8_t threshold = getThreshold(i_thrName);
    uint32_t interval = ThresholdResolution::NONE;

    if( (MfgThresholdFileCommon::INFINITE_LIMIT_THR) <= threshold )
    {
        PRDF_TRAC("MfgThresholdMgr::getThresholdP: "
                  "infinite threshold: 0x%x", i_thrName);
        interval = ThresholdResolution::ONE_SEC;
    }

    ThresholdResolution::ThresholdPolicy l_policy( threshold, interval );

    return &(iv_thrs.get(l_policy));
}
void PressureBarrier::wait(int pressure) {
	spinLock.lock();
	this->pressure += pressure;

	bool doOpen = false;
	if (barrierClosed && this->pressure >= getThreshold())
		doOpen = true;

	spinLock.unLock();

	if (doOpen)
		barrierClosed = false;

	// wait for barrier to open
	while (barrierClosed)
		;
}
예제 #12
0
bool FeatureFloodCount::isNewFeatureOrConnectedRegion(const DofObject * dof_object, std::size_t current_index, FeatureData * & feature, unsigned int & /*new_id*/)
{
  auto threshold = getThreshold(current_index, feature);

  // Get the value of the current variable for the current entity
  Real entity_value;
  if (_is_elemental)
  {
    const Elem * elem = static_cast<const Elem *>(dof_object);
    std::vector<Point> centroid(1, elem->centroid());
    _subproblem.reinitElemPhys(elem, centroid, 0);
    entity_value = _vars[current_index]->sln()[0];
  }
  else
    entity_value = _vars[current_index]->getNodalValue(*static_cast<const Node *>(dof_object));

  // This entity hasn't been marked, is it in a feature?  We must respect
  // the user-selected value of _use_less_than_threshold_comparison.
  return ((_use_less_than_threshold_comparison && (entity_value >= threshold)) ||
          (!_use_less_than_threshold_comparison && (entity_value <= threshold)));
}
예제 #13
0
bool SelectNodesOP::onDraw() const
{
	if (DrawRectangleOP::onDraw()) return true;

	if (m_nodeSelection.empty()) return false;

	std::vector<Vector> nodes;
	int count = 0;
	for (size_t i = 0, n = m_nodeSelection.size(); i < n; ++i)
		count += m_nodeSelection[i]->selectedNodes.size();
	nodes.reserve(count);

	for (size_t i = 0, n = m_nodeSelection.size(); i < n; ++i)
	{
		const std::vector<Vector>& selectedNodes = m_nodeSelection[i]->selectedNodes;
		copy(selectedNodes.begin(), selectedNodes.end(), back_inserter(nodes));
	}

	PrimitiveDraw::drawCircles(nodes, getThreshold(), true, 2, Colorf(0.8f, 0.4f, 0.4f));

	return false;
}
예제 #14
0
	/**
	 * Starting from the SPECIE node, the function parses all the REGUL tags and reads the data from them.
	 * If not provided, attributes are defaulted - threshold to 1, label to Label::free
	 */
	static void parseRegulations(const rapidxml::xml_node<> * const specie_node, Model & model) {
		// Get ID of the regulated component
		string name;
		XMLHelper::getAttribute(name, specie_node, "name", true);
		const SpecieID t_ID = ModelTranslators::findID(model, name);

		// Cycle through REGUL TAGS
		for (auto regulation : XMLHelper::NodesRange(specie_node, "REGUL", true)) {
			string label;
			if (!XMLHelper::getAttribute(label, regulation, "label", false))
				label = Label::Free;
			SpecieID s_ID = getSourceID(regulation, t_ID, model);
			size_t threshold = getThreshold(regulation, t_ID, s_ID, model);

			// Add a new regulation to the specified target
			model.addRegulation(s_ID, t_ID, threshold, label);
		}

		// Sort regulators lexicographically
		rng::sort(model.species[t_ID].regulations, [](const Model::Regulation & A, const Model::Regulation & B) {
			return A.source < B.source;
		});
	}
char MSAConsensusAlgorithmDefault::getConsensusCharAndScore(const MAlignment& msa, int pos, int& cnt, const QVector<qint64> &seqIdx) const {
    //TODO: use var-length array!
    QVector<QPair<int, char> > freqs(32);
    int ch = MAlignment_GapChar;
    int nSeq = seqIdx.isEmpty() ? msa.getNumRows() : seqIdx.size();
    for (int seq = 0; seq < nSeq; seq++) {
        uchar c = (uchar)msa.charAt( seqIdx.isEmpty() ? seq : seqIdx[ seq ],
                                     pos);
        if (c >= 'A' && c <= 'Z') {
            int idx = c - 'A';
            assert(idx >=0 && idx <= freqs.size());
            freqs[idx].first++;
            freqs[idx].second = c;
        }
    }
    qSort(freqs);
    int p1 = freqs[freqs.size()-1].first;
    int p2 = freqs[freqs.size()-2].first;
    if (p1 == 0 || (p1 == 1 && nSeq > 1)) {
        ch = MAlignment_GapChar;
        cnt = 0;
    } else {
        int c1 = freqs[freqs.size()-1].second;
        ch = p2 == p1 ? '+' : c1;
        cnt = p1;
    }

    //lowercase alpha chars with < threshold% content
    int currentThreshold = getThreshold();
    int cntToUseLowerCase = int(currentThreshold / 100.0 * nSeq);
    if (cnt < cntToUseLowerCase && (ch >='A' && ch <='Z')) {
        ch = ch + ('a'-'A');
    }

    return ch;
}
예제 #16
0
void canny(FILE* inputImageFile, FILE* outputMagnitudes, FILE* outputPeaks, FILE* outputFinal, double sigma){
    Mask mask;
    int picBuffer[PICSIZE][PICSIZE];
    double itsMagnitudes[PICSIZE][PICSIZE];
    double maxMagnitude;
    GradientVector usingGradients;
    double peaks[PICSIZE][PICSIZE];
    double final[PICSIZE][PICSIZE];

    readImageTo(picBuffer, inputImageFile);
    mask = generateSmoothenerMask(sigma);
    usingGradients = calculateGradients(picBuffer, mask);
    calculateMagnitudes(usingGradients, mask.radius, itsMagnitudes);
    maxMagnitude = findMaxValue(itsMagnitudes);
    scaleImageWithRespectTo(maxMagnitude, itsMagnitudes);

    findPeaks(itsMagnitudes, usingGradients, mask.radius, peaks);
    Threshold threshold = getThreshold(itsMagnitudes);
    applyHysteresisThresholdTo(itsMagnitudes, usingGradients, mask.radius, 
                                peaks, threshold, final);
    writeTo(outputMagnitudes, itsMagnitudes);
    writeTo(outputPeaks, peaks);
    writeTo(outputFinal, final);
}
예제 #17
0
void QmitkIsoSurface::CreateSurface()
{
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  if (m_MitkImage != NULL)
  {
    // Value Gauss
    // float gsDev = 1.5;

    // Value for DecimatePro
    float targetReduction = 0.05;

    // ImageToSurface Instance
    mitk::DataNode::Pointer node = m_Controls->m_ImageSelector->GetSelectedNode();

    mitk::ManualSegmentationToSurfaceFilter::Pointer filter = mitk::ManualSegmentationToSurfaceFilter::New();
    if (filter.IsNull())
    {
      std::cout << "NULL Pointer for ManualSegmentationToSurfaceFilter" << std::endl;
      return;
    }

    filter->SetInput(m_MitkImage);
    filter->SetGaussianStandardDeviation(0.5);
    filter->SetUseGaussianImageSmooth(true);
    filter->SetThreshold(getThreshold()); // if( Gauss ) --> TH manipulated for vtkMarchingCube

    filter->SetTargetReduction(targetReduction);

    int numOfPolys = filter->GetOutput()->GetVtkPolyData()->GetNumberOfPolys();
    if (numOfPolys > 2000000)
    {
      QApplication::restoreOverrideCursor();
      if (QMessageBox::question(NULL,
                                "CAUTION!!!",
                                "The number of polygons is greater than 2 000 000. If you continue, the program might "
                                "crash. How do you want to go on?",
                                "Proceed anyway!",
                                "Cancel immediately! (maybe you want to insert an other threshold)!",
                                QString::null,
                                0,
                                1) == 1)
      {
        return;
      }
      QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    }
    mitk::DataNode::Pointer surfaceNode = mitk::DataNode::New();
    surfaceNode->SetData(filter->GetOutput());

    int layer = 0;

    ++m_SurfaceCounter;
    std::ostringstream buffer;
    buffer << m_SurfaceCounter;
    std::string surfaceNodeName = "Surface " + buffer.str();

    node->GetIntProperty("layer", layer);
    surfaceNode->SetIntProperty("layer", layer + 1);
    surfaceNode->SetProperty("Surface", mitk::BoolProperty::New(true));
    surfaceNode->SetProperty("name", mitk::StringProperty::New(surfaceNodeName));

    this->GetDataStorage()->Add(surfaceNode, node);

    // to show surfaceContur
    surfaceNode->SetColor(m_RainbowColor.GetNextColor());
    surfaceNode->SetVisibility(true);

    mitk::IRenderWindowPart *renderPart = this->GetRenderWindowPart();
    if (renderPart)
    {
      renderPart->RequestUpdate();
    }
  }

  QApplication::restoreOverrideCursor();
}
예제 #18
0
bool XAGYLWheel::ISNewNumber (const char *dev, const char *name, double values[], char *names[], int n)
{
    if(strcmp(dev,getDeviceName())==0)
    {               
        if (!strcmp(OffsetNP.name, name))
        {
            bool rc_offset=true;
            for (int i=0; i < n; i++)
            {
                if (!strcmp(names[i], OffsetN[i].name))
                {
                    while (values[i] != OffsetN[i].value && rc_offset)
                    {
                        if (values[i] > OffsetN[i].value)
                            rc_offset = setOffset(i, 1);
                        else
                            rc_offset = setOffset(i, -1);
                    }
                }

            }

            OffsetNP.s = rc_offset ? IPS_OK : IPS_ALERT;
            IDSetNumber(&OffsetNP, NULL);
            return true;
        }

        if (!strcmp(SettingsNP.name, name))
        {
            double newSpeed, newJitter, newThreshold, newPulseWidth;
            for (int i=0; i < n; i++)
            {
                if (!strcmp(names[i], SettingsN[SET_SPEED].name))
                    newSpeed = values[i];
                else if (!strcmp(names[i], SettingsN[SET_JITTER].name))
                    newJitter = values[i];
                if (!strcmp(names[i], SettingsN[SET_THRESHOLD].name))
                    newThreshold = values[i];
                if (!strcmp(names[i], SettingsN[SET_PULSE_WITDH].name))
                    newPulseWidth = values[i];
            }

            bool rc_speed=true, rc_jitter=true, rc_threshold=true, rc_pulsewidth=true;

            if (newSpeed != SettingsN[SET_SPEED].value)
            {
                rc_speed = setCommand(SET_SPEED, newSpeed);
                getMaximumSpeed();
            }

            // Jitter
            while (newJitter != SettingsN[SET_JITTER].value && rc_jitter)
            {
                if (newJitter > SettingsN[SET_JITTER].value)
                {
                    rc_jitter &= setCommand(SET_JITTER, 1);
                    getJitter();
                }
                else
                {
                    rc_jitter &= setCommand(SET_JITTER, -1);
                    getJitter();
                }
            }

            // Threshold
            while (newThreshold != SettingsN[SET_THRESHOLD].value && rc_threshold)
            {
                if (newThreshold > SettingsN[SET_THRESHOLD].value)
                {
                    rc_threshold &= setCommand(SET_THRESHOLD, 1);
                    getThreshold();
                }
                else
                {
                    rc_threshold &= setCommand(SET_THRESHOLD, -1);
                    getThreshold();
                }
            }

            // Pulse width
            while (firmwareVersion >= 3 && newPulseWidth != SettingsN[SET_PULSE_WITDH].value && rc_pulsewidth)
            {
                if (newPulseWidth> SettingsN[SET_PULSE_WITDH].value)
                {
                    rc_pulsewidth &= setCommand(SET_PULSE_WITDH, 1);
                    getPulseWidth();
                }
                else
                {
                    rc_pulsewidth &= setCommand(SET_PULSE_WITDH, -1);
                    getPulseWidth();
                }
            }

            if (rc_speed && rc_jitter && rc_threshold && rc_pulsewidth)
                SettingsNP.s = IPS_OK;
            else
                SettingsNP.s = IPS_ALERT;

            IDSetNumber(&SettingsNP, NULL);

            return true;
        }
    }

    return INDI::FilterWheel::ISNewNumber(dev, name, values, names, n);
}
예제 #19
0
// エフェクト処理
int effect(ImageData *img,ImageData *outimg)
{
	int val;
	int i,j;
	int x,y;
	int xx,yy;
	int pix;
	int rr,gg,bb;
	int th,th_e;
	int *hist2;
	int ehist[256];
	int sam;
	int a;
	int hist[256];
	int fil[3][3]={
			 0, 1, 0,
			 1,-4, 1,
			 0, 1, 0
	};
	int x1,y1,x2,y2;
	Pixel col;

	x1=0;
	y1=0;
	x2=img->width-1;
	y2=img->height-1;

	// ptileのパラメータ
	a=90;
	// ヒストグラム計算
	for(i=0;i<256;i++) {
		hist[i]=0;
		ehist[i]=0;
	}
	hist2=malloc(sizeof(int)*256*256);
	for(y=0;y<256;y++) {
		for(x=0;x<256;x++) {
			hist2[x+y*256]=0;
		}
	}
	for(y=y1;y<=y2;y++) {
		for(x=x1;x<=x2;x++) {
			val = getPixel(img,x,y,&col);	//画像上の画素情報を取得
			rr=col.r;
			sam=0;
			for(yy=0;yy<3;yy++) {
				for(xx=0;xx<3;xx++) {
					val = getPixel(img,x+xx-1,y+yy-1,&col);	//画像上の画素情報を取得
					gg=col.r;
					sam+=(gg*fil[xx][yy]);
				}
			}
			if(sam<0) sam=0;
			if(sam>255) sam=255;
			hist2[rr+sam*256]++;
			ehist[sam]++;
		}
	}
	th_e=getThresholdPtile(ehist,256,a);
	for(i=0;i<256;i++) {
		for(j=th_e;j<256;j++) {
			hist[i]+=hist2[i+j*256];
		}
	}
	free(hist2);
	th=getThreshold(hist,256);

	for(y=y1;y<=y2;y++) {
		for(x=x1;x<=x2;x++) {
			val = getPixel(img,x,y,&col);	//画像上の画素情報を取得
			rr=col.r;
			gg=col.g;
			bb=col.b;
			if(th<rr) rr=255;
			else rr=0;
			if(th<gg) gg=255;
			else gg=0;
			if(th<bb) bb=255;
			else bb=0;
			col.r = rr;
			col.g = gg;
			col.b = bb;
			setPixel(outimg,x,y,&col);	// 画像に値をセットする
		}
	}
	return TRUE;
}
예제 #20
0
void ARTracker::doThreshold(cv::Mat& outputMat, cv::Mat& greyMat){
    cv::threshold(greyMat, outputMat, getThreshold(), 255, cv::THRESH_BINARY_INV);        
}
예제 #21
0
/* @brief	For bases, differentiate by (base, #occur); For deletions,
 * 			differentiate by (D, #); for insertions, differentiate by
 * 			(I, ins_str)
 *
 * @param	[nuvars]: vars that were not previously called in [gvars]
 */
void pileup (var_t& nuvars, pileup_list_t& nulist, pileup_list_t& rmlist,
		const pileup_list_t& pileuplist, const var_t& gvars,
		const col_t& col, const std::vector<jeb_t>& jeb,
		const GlobalParam& gParam, int iter) {

	//{
	//	std::cout << "pos = " << col.ref_pos << "\n";
 	//}
	int threshold = INT_MAX;

 	// ---------- generate profile and calculate lamda -------------
	pileup_profile_t profile_info;
	strset_t vars;
	if (iter == 0) { // first iteration pop up the pic

		pileup_profiling (profile_info, col, jeb, gParam);

		if (profile_info.lamda_L) {
			threshold = getThreshold (profile_info.lamda_L,
					profile_info.p_L, gParam.bonferroni);
			// ----------------- analyze profile and call vars ------------------
			if (call_pileup_variant (vars, threshold, profile_info.LProfile))	{
				nulist.L.insert(col.ref_pos);
			}
		}

		if (profile_info.lamda_S) {
			threshold = getThreshold (profile_info.lamda_S,
					profile_info.p_S, gParam.bonferroni);
			if (call_pileup_variant (vars, threshold, profile_info.SProfile)) {
				nulist.S.insert(col.ref_pos);
			}
		}

		add_var_entry (nuvars, col.ref_pos, vars);

		{
		//	debug_print_var (nuvars);
		}
	} else { // not the first iteration
		if (pileuplist.L.count(col.ref_pos) || pileuplist.S.count(col.ref_pos)) {

			pileup_profiling (profile_info, col, jeb, gParam);

			if (profile_info.lamda_L && pileuplist.L.count(col.ref_pos)) {
				threshold = getThreshold (profile_info.lamda_L,
						profile_info.p_L, gParam.bonferroni);
				if (! call_pileup_variant (vars, threshold, profile_info.LProfile)){
					rmlist.L.insert(col.ref_pos);
				}
			}

			if (profile_info.lamda_S && pileuplist.S.count(col.ref_pos)) {
				threshold = getThreshold (profile_info.lamda_S,
						profile_info.p_S, gParam.bonferroni);
				if (! call_pileup_variant (vars, threshold, profile_info.SProfile)) {
					rmlist.S.insert(col.ref_pos);
				}
			}

			// identify variants that were not yet in [gvars]
			var_t::const_iterator it_gvar = gvars.find(col.ref_pos);
			if (it_gvar != gvars.end()) {
				strset_t diffs;
				strset_t::const_iterator it_s = vars.begin();
				for (; it_s != vars.end(); ++ it_s){
					if (!it_gvar->second.count(*it_s)) diffs.insert(*it_s);
				}
				if (diffs.size()) add_var_entry(nuvars, col.ref_pos, diffs);
			} else add_var_entry (nuvars, col.ref_pos, vars);

			{
				//debug_print_var (nuvars);
			}

		} // if

	} // else
} // pileup
예제 #22
0
float TintonationView::getThreshold(int accInteger) {
		return getThreshold((Eaccuracy)accInteger);
}
예제 #23
0
void TintonationView::setAccuracy(int accuracy) {
  m_accuracy = (Eaccuracy)qBound(0, accuracy, 5);
	m_accurValue = getThreshold(m_accuracy);
  m_accurValue *= INT_FACTOR;
  resizeEvent(0);
}
예제 #24
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void Watershed::setupFilterParameters()
{
  FilterParameterVector parameters;
  parameters.push_back(FilterParameter::New("Image Data Array", "SelectedCellArrayPath", FilterParameterWidgetType::DataArraySelectionWidget, getSelectedCellArrayPath(), false, ""));
  parameters.push_back(FilterParameter::New("Feature Ids Array", "FeatureIdsArrayName", FilterParameterWidgetType::StringWidget, getFeatureIdsArrayName(), false, ""));
  parameters.push_back(FilterParameter::New("Threshold", "Threshold", FilterParameterWidgetType::DoubleWidget, getThreshold(), false));
  parameters.push_back(FilterParameter::New("Level", "Level", FilterParameterWidgetType::DoubleWidget, getLevel(), false));
  setFilterParameters(parameters);
}
예제 #25
0
	string ThresholdLayer::convet2CaffeFormat()
	{
		string layerStrStart = "layer\n{\n";
		string layerStrEnd = "}";

		string nameStrStart = "\tname: \"";
		string nameStrEnd = "\"\n";

		string typeStrStart = "\ttype: \"";
		string typeStrEnd = "\"\n";

		string topStrStart = "\ttop: \"";
		string topStrEnd = "\"\n";

		string bottomStrStart = "\tbottom: \"";
		string bottomStrEnd = "\"\n";

		string thresholdParamStrStart = "\tthreshold_param\n\t{\n";
		string thresholdParamStrEnd = "\t}\n";

		string thresholdStrStart = "\t\tthreshold: ";
		string thresholdStrEnd = "\n";

		string phaseStrStart = "\tinclude:\n\t{\n";		
		string phaseStrEnd = "\t}\n";

		string phaseStateStrStart = "\t\tphase: ";
		string phaseStateStrEnd = "\n";

		string outStr = layerStrStart + 
						nameStrStart  + mName         + nameStrEnd + 
						typeStrStart  + getLayerType() + typeStrEnd;

		for(size_t i = 0; i < mTops->size(); i++)
		{
			outStr = outStr + topStrStart + (*mTops)[i] + topStrEnd;
		}

		for(size_t i = 0; i < mBottoms->size(); i++)
		{
			outStr = outStr + bottomStrStart + (*mBottoms)[i] + bottomStrEnd;
		}

		outStr = outStr + thresholdParamStrStart;

		if (getThreshold() != 0)
		{
			outStr += thresholdStrStart + to_string(getThreshold()) + thresholdStrEnd;
		}

		outStr += thresholdParamStrEnd;

		if (mPhase != Phase::BOTH)
		{
			outStr += phaseStrStart + phaseStateStrStart;

			if (mPhase == Phase::TRAIN)
			{
				outStr += "TRAIN";
			}
			else if (mPhase == Phase::TEST)
			{
				outStr += "TEST";
			}

			outStr += phaseStateStrEnd + phaseStrEnd;
		}
		
		outStr += layerStrEnd;

		return outStr;
	}
예제 #26
0
void FaceRecognizer::predict(InputArray src, CV_OUT int &label, CV_OUT double &confidence) const {
    Ptr<MinDistancePredictCollector> collector = MinDistancePredictCollector::create(getThreshold());
    predict(src, collector, 0);
    label = collector->getLabel();
    confidence = collector->getDist();
}
예제 #27
0
void Joystick::setX(float x) {
    if ( (x > 0.0f && x < getThreshold()) || (x < 0.0f && x > getThreshold() * -1.0f) ) {
        x = 0.0f;
    }
    m_x = x;
}
예제 #28
0
bool SelectNodesOP::onMouseLeftDown(int x, int y)
{
	Vector pos = m_editPanel->transPosScreenToProject(x, y);
	ChainSelectedNodes* selected = NULL;
	m_shapeImpl->traverseShapes(PosQueryVisitor(pos, &selected), e_visible);
	if (selected)
	{
		if (wxGetKeyState(WXK_CONTROL))
		{
			bool isExist = false;
			for (size_t i = 0, n = m_nodeSelection.size(); i < n && !isExist; ++i)
			{
				ChainSelectedNodes* chainNodes = m_nodeSelection[i];
				if (chainNodes->chain != selected->chain) continue;
				for (size_t j = 0, m = chainNodes->selectedNodes.size(); j < m && !isExist; ++j)
				{
					if (Math::getDistance(pos, chainNodes->selectedNodes[j]) < getThreshold())
					{
						chainNodes->selectedNodes.erase(chainNodes->selectedNodes.begin() + j);
						if (chainNodes->selectedNodes.empty())
							m_nodeSelection.erase(m_nodeSelection.begin() + i);
						isExist = true;
					}
				}
			}

			if (!isExist)
				m_nodeSelection.push_back(selected);
			else
				delete selected;
		}
		else
		{
			bool isExist = false;
			for (size_t i = 0, n = m_nodeSelection.size(); i < n && !isExist; ++i)
			{
				ChainSelectedNodes* chainNodes = m_nodeSelection[i];
				if (chainNodes->chain != selected->chain) continue;
				for (size_t j = 0, m = chainNodes->selectedNodes.size(); j < m && !isExist; ++j)
				{
					if (Math::getDistance(pos, chainNodes->selectedNodes[j]) < getThreshold())
						isExist = true;
				}
			}

			if (!isExist)
			{
				clearSelectedNodes();
				m_nodeSelection.push_back(selected);
			}
			else
				delete selected;
		}

		m_firstPos.setInvalid();
	}
	else
	{
		DrawRectangleOP::onMouseLeftDown(x, y);
		m_firstPos = pos;
		if (!wxGetKeyState(WXK_CONTROL))
			clearSelectedNodes();
		m_editPanel->Refresh();
	}

	return false;
}
void sortGenes(struct sqlConnection *conn)
/* Put up sort gene page. */
{
cartWebStart(cart, database, "Finding Candidate Genes for Gene Sorter");
if (!hgNearOk(database))
    errAbort("Sorry, gene sorter not available for this database.");

/* Get list of regions. */
struct genoGraph *gg = ggFirstVisible();
double threshold = getThreshold();
struct bed3 *bed, *bedList = regionsOverThreshold(gg);

/* Figure out what table and column are the sorter's main gene set. */
struct hash *genomeRa = hgReadRa(genome, database, "hgNearData", 
	"genome.ra", NULL);
char *geneTable = hashMustFindVal(genomeRa, "geneTable");
char *idColumn = hashMustFindVal(genomeRa, "idColumn");

/* if marker labels were present when the file was uploaded, they are saved here */
char cgmName[256];
safef(cgmName, sizeof(cgmName), "%s.cgm", gg->binFileName);
struct lineFile *m = lineFileMayOpen(cgmName, TRUE);
char *cgmRow[4];
cgmRow[0] = "";    /* dummy row */
cgmRow[1] = "";
cgmRow[2] = "0";
cgmRow[3] = "0";

FILE *g = NULL;
int markerCount = 0;
struct tempName snpTn;

if (m)
    {
    /* Create custom column output file. */
    trashDirFile(&snpTn, "hgg", "marker", ".mrk");  
    g = mustOpen(snpTn.forCgi, "w");
    fprintf(g, 
	"column name=\"%s Markers\" shortLabel=\"%s Markers over threshold\" longLabel=\"%s Markers in regions over threshold\" " 
	"visibility=on priority=99 "
        "\n"
        , gg->shortLabel
        , gg->shortLabel
        , gg->shortLabel
	);
    }

/*** Build up hash of all transcriptHash that are in region. */
struct hash *transcriptHash = hashNew(16);

/* This loop handles one chromosome at a time.  It depends on
 * the bedList being sorted by chromosome. */
for (bed = bedList; bed != NULL; )
    {

    /* Make binKeeper and stuff in all regions in this chromosome into it. */
    char *chrom = bed->chrom;
    int chromSize = hChromSize(database, chrom);
    struct binKeeper *bk = binKeeperNew(0, chromSize);
    while (bed != NULL && sameString(chrom, bed->chrom))
	{
	binKeeperAdd(bk, bed->chromStart, bed->chromEnd, bed);
	bed = bed->next;
	}

    struct binKeeper *bkGenes = NULL;
    if (m)
       bkGenes = binKeeperNew(0, chromSize);

    /* Query database to find out bounds of all genes on this chromosome
     * and if they overlap any of the regions then put them in the hash. */
    char query[512];
    safef(query, sizeof(query), 
    	"select name,txStart,txEnd from %s where chrom='%s'", geneTable, chrom);
    struct sqlResult *sr = sqlGetResult(conn, query);
    char **row;
    while ((row = sqlNextRow(sr)) != NULL)
        {
	char *name = row[0];
	int start = sqlUnsigned(row[1]);
	int end = sqlUnsigned(row[2]);
	if (binKeeperAnyOverlap(bk, start, end))
	    {
	    hashStore(transcriptHash, name);
	    if (m)
		binKeeperAdd(bkGenes, start, end, cloneString(name));
	    }
	}
    sqlFreeResult(&sr);

    if (m)
	{
	/* Read cgm file if it exists, looking at all markers on this chromosome
	 * and if they overlap any of the regions and genes then output them. */
	do 
	    {
	    // marker, chrom, chromStart, val
	    char *marker = cgmRow[0];
	    char *chr = cgmRow[1];
	    int start = sqlUnsigned(cgmRow[2]);
	    int end = start+1;
	    double val = sqlDouble(cgmRow[3]);
            int cmp = strcmp(chr,chrom);
            if (cmp > 0)
                break;
            if (cmp == 0)
		{
		if (val >= threshold)
		    {
		    struct binElement *el, *bkList = binKeeperFind(bkGenes, start, end);
		    for (el = bkList; el; el=el->next)
			{
			/* output to custom column trash file */
			fprintf(g, "%s %s\n", (char *)el->val, marker);
			}
		    if (bkList)
			{
			++markerCount;
			slFreeList(&bkList);
			}
		    }
		}
	    }
	while (lineFileRow(m, cgmRow));
	}

    /* Clean up for this chromosome. */
    binKeeperFree(&bk);

    if (m)
	{
	/* For speed, we do not free up the values (cloned the kg names earlier) */
	binKeeperFree(&bkGenes);  
	}

    }

/* Get list of all transcripts in regions. */
struct hashEl *el, *list = hashElListHash(transcriptHash);

/* Create file with all matching gene IDs. */
struct tempName keyTn;
trashDirFile(&keyTn, "hgg", "key", ".key");
FILE *f = mustOpen(keyTn.forCgi, "w");
for (el = list; el != NULL; el = el->next)
    fprintf(f, "%s\n", el->name);
carefulClose(&f);

/* Print out some info. */
hPrintf("Thresholding <i>%s</i> at %g. ", gg->shortLabel, threshold);
hPrintf("There are %d regions covering %lld bases.<BR>\n",
    slCount(bedList), bedTotalSize((struct bed*)bedList) );
hPrintf("Installed a Gene Sorter filter that selects only genes in these regions.<BR>\n");
if (m)
    {
    hPrintf("There are %d markers in the regions over threshold that overlap knownGenes.<BR>\n", markerCount);
    hPrintf("Installed a Gene Sorter custom column called \"%s Markers\" with these markers.<BR>\n", gg->shortLabel);
    }

/* close custom column output file */
if (m)
    {
    lineFileClose(&m);
    carefulClose(&g);
    }

/* Stuff cart variable with name of file. */
char keyCartName[256];
safef(keyCartName, sizeof(keyCartName), "%s%s.keyFile",
	advFilterPrefix, idColumn);
cartSetString(cart, keyCartName, keyTn.forCgi);

cartSetString(cart, customFileVarName, snpTn.forCgi);

char snpVisCartNameTemp[256];
char *snpVisCartName = NULL;
safef(snpVisCartNameTemp, sizeof(snpVisCartNameTemp), "%s%s Markers.vis",
	colConfigPrefix, gg->shortLabel);
snpVisCartName = replaceChars(snpVisCartNameTemp, " ", "_");
cartSetString(cart, snpVisCartName, "1");
freeMem(snpVisCartName);

hPrintf("<FORM ACTION=\"../cgi-bin/hgNear\" METHOD=GET>\n");
cartSaveSession(cart);
hPrintf("<CENTER>");
cgiMakeButton("submit", "go to gene sorter");
hPrintf("</CENTER>");
hPrintf("</FORM>");

cartWebEnd();
}
예제 #30
0
void QmitkIsoSurface::CreateSurface()
{
  QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
  if(m_MitkImage != NULL)
  {
    //Value Gauss
    //float gsDev = 1.5;

    //Value for DecimatePro
    float targetReduction = 0.05;

    //ImageToSurface Instance
    mitk::DataNode::Pointer node = m_Controls->m_ImageSelector->GetSelectedNode();

    /*
    mitk::DataTreeIteratorClone  iteratorOnImageToBeSkinExtracted;

    iteratorOnImageToBeSkinExtracted = m_Controls->m_ImageSelector->GetFilter()->GetIteratorToSelectedItem();
    if(iteratorOnImageToBeSkinExtracted.IsNull())
    {
      iteratorOnImageToBeSkinExtracted = CommonFunctionality::GetIteratorToFirstImage(m_DataTreeIterator.GetPointer());
    }
    */

    mitk::ManualSegmentationToSurfaceFilter::Pointer filter = mitk::ManualSegmentationToSurfaceFilter::New();
    if (filter.IsNull())
    {
      std::cout<<"NULL Pointer for ManualSegmentationToSurfaceFilter"<<std::endl;
      return;
    }

    filter->SetInput( m_MitkImage );
    filter->SetGaussianStandardDeviation( 0.5 );
    filter->SetUseGaussianImageSmooth( true );
    filter->SetThreshold( getThreshold()); //if( Gauss ) --> TH manipulated for vtkMarchingCube

    filter->SetTargetReduction( targetReduction );


    int numOfPolys = filter->GetOutput()->GetVtkPolyData()->GetNumberOfPolys();
    if(numOfPolys>2000000)
    {
      QApplication::restoreOverrideCursor();
      if(QMessageBox::question(NULL, "CAUTION!!!", "The number of polygons is greater than 2 000 000. If you continue, the program might crash. How do you want to go on?", "Proceed anyway!", "Cancel immediately! (maybe you want to insert an other threshold)!",QString::null,0 ,1)==1)
      {

        return;
      }
          QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
    }
    mitk::DataNode::Pointer surfaceNode = mitk::DataNode::New();
    surfaceNode->SetData( filter->GetOutput() );

    int layer = 0;

    ++m_SurfaceCounter;
    std::ostringstream buffer;
    buffer << m_SurfaceCounter;
    std::string surfaceNodeName = "Surface " + buffer.str();

    node->GetIntProperty("layer", layer);
    surfaceNode->SetIntProperty("layer", layer+1);
    surfaceNode->SetProperty("Surface", mitk::BoolProperty::New(true));
    surfaceNode->SetProperty("name", mitk::StringProperty::New(surfaceNodeName));

    /*
    mitk::DataTreeIteratorClone iteratorClone = m_DataTreeIterator;
    bool isSurface = false;

    while(!(iteratorClone->IsAtEnd())&&(isSurface == false))
    {
      iteratorClone->Get()->GetBoolProperty("Surface", isSurface);
      if(isSurface == false)
      {
        ++iteratorClone;
      }
    }

    iteratorClone= iteratorOnImageToBeSkinExtracted;
    iteratorClone->Add(surfaceNode);
    iteratorClone->GetTree()->Modified();
    */
    this->GetDefaultDataStorage()->Add(surfaceNode, node);

    mitk::Surface::Pointer surface = filter->GetOutput();

    //to show surfaceContur
    surfaceNode->SetColor( m_RainbowColor.GetNextColor() );
    surfaceNode->SetVisibility(true);

    this->GetActiveStdMultiWidget()->RequestUpdate();

  }//if m_MitkImage != NULL

  QApplication::restoreOverrideCursor();
}