Ejemplo n.º 1
0
void DataProcessor::calculateFilterValues(std::vector<int> selectedOptions){
    int numSelected = selectedOptions.size();
    std::shared_ptr<Histogram> histogram;
    float mean, standardDeviation, filterMid, filterWidth;

    _filterValues = glm::vec2(0.0);
    if(numSelected <= 0) return;

    if(!_histograms.empty()){
        for(int option : selectedOptions){
            if(!_useHistogram){
                mean = (1.0/_numValues[option])*_sum[option];
                standardDeviation = _standardDeviation[option];
                histogram = _histograms[option];
                
                filterMid = histogram->highestBinValue(_useHistogram);
                filterWidth = mean+histogram->binWidth();
                
                filterMid = normalizeWithStandardScore(filterMid, mean, standardDeviation, _normValues);
                filterWidth = fabs(0.5-normalizeWithStandardScore(filterWidth, mean, standardDeviation, _normValues));
            }else{
                Histogram hist = _histograms[option]->equalize();
                filterMid = hist.highestBinValue(true);
                std::cout << filterMid << std::endl;
                filterWidth = 1.f/512.f;
            }

             _filterValues += glm::vec2(filterMid, filterWidth);

        }
        _filterValues /= numSelected;   
    }
}
Ejemplo n.º 2
0
JSBool
JSHistogram_Add(JSContext *cx, unsigned argc, jsval *vp)
{
  if (!argc) {
    JS_ReportError(cx, "Expected one argument");
    return JS_FALSE;
  }

  jsval v = JS_ARGV(cx, vp)[0];

  if (!(JSVAL_IS_NUMBER(v) || JSVAL_IS_BOOLEAN(v))) {
    JS_ReportError(cx, "Not a number");
    return JS_FALSE;
  }

  int32_t value;
  if (!JS_ValueToECMAInt32(cx, v, &value)) {
    return JS_FALSE;
  }

  if (TelemetryImpl::CanRecord()) {
    JSObject *obj = JS_THIS_OBJECT(cx, vp);
    if (!obj) {
      return JS_FALSE;
    }

    Histogram *h = static_cast<Histogram*>(JS_GetPrivate(obj));
    if (h->histogram_type() == Histogram::BOOLEAN_HISTOGRAM)
      h->Add(!!value);
    else
      h->Add(value);
  }
  return JS_TRUE;
}
Ejemplo n.º 3
0
Inelastic_Event_Generator::~Inelastic_Event_Generator() 
{
  msg_Info()<<"In "<<METHOD<<"(out = "<<m_output<<")\n";
  if (m_output) {
    if (m_analyse) {
      msg_Info()
	<<"Mean number of number of ladders: "
	<<"naive = "<<m_histograms[string("N_ladder_naive")]->Average()<<", "
	<<"start = "<<m_histograms[string("N_ladder_start")]->Average()<<", "
	<<"prim = "<<m_histograms[string("N_ladder_prim")]->Average()<<", "
	<<"true = "<<m_histograms[string("N_ladder_true")]->Average()<<".\n";
    }
    msg_Info()<<"Errors: \n"
	      <<"   Not able to connect blobs "<<m_connectblobs<<";\n"
	      <<"   Wrong colours from ladder "<<m_laddercols<<";\n"
	      <<"   Not able to update colours in event "<<m_updatecols<<".\n";
  }
  if (m_histograms.empty() || !m_analyse) return;
  Histogram * histo;
  string name;
  for (map<string,Histogram *>::iterator hit=m_histograms.begin();
       hit!=m_histograms.end();hit++) {
    histo = hit->second;
    name  = string("Ladder_Analysis/")+hit->first+string(".dat");
    histo->Finalize();
    histo->Output(name);
    delete histo;
  }
  m_histograms.clear();
}
Ejemplo n.º 4
0
 ~HistogramFixture() {
     BOOST_CHECK_EQUAL(h.getNumSamples(), 14);
     BOOST_CHECK_EQUAL(h.getPercentile(0.5), 5);
     BOOST_CHECK_EQUAL(h.getPercentile(0.75), 7);
     BOOST_CHECK_EQUAL(h.getPercentile(0.2), 2);
     BOOST_CHECK_EQUAL(h.getFraction(2), 3.0/14.0);
 }
void EqualizeAlgorithm::doAlgorithm(Image& img) {
	unsigned char * rawData = img.getRawData();
	int bpp = img.getBPP();
	int height = img.getHeight();
	int width = img.getWidth();
	int pitch = img.getPitch();

	//step 1
	//Create the histogram
	Histogram h;
	double * histo = h.normalizeHistogram(rawData, bpp, height, width, pitch, size);
	//step 2
	//Modify the histogram for usage
	double * histoModified = new double[size];
	histoModified[0] = histo[0];
	unsigned int x, y;
	for (x = 1; x < size; x++) {
		histoModified[x] = histoModified[x - 1] + histo[x];
	}
	//step 3
	//Change the color values according to the modified histogram
	for (y = 0; y < height; y++) {
		for (x = 0; x < pitch; x += bpp) {
			rawData[y * pitch + x + RED] = histoModified[rawData[y * pitch + x + RED]] * size;
			rawData[y * pitch + x + GREEN] = histoModified[rawData[y * pitch + x + GREEN]] * size;
			rawData[y * pitch + x + BLUE] = histoModified[rawData[y * pitch + x + BLUE]] * size;
		}
	}
}
Ejemplo n.º 6
0
  void SpectrumWidget::showMetaDistribution(const String& name)
  {
    Histogram<> dist = createMetaDistribution_(name);
    HistogramDialog dw(dist);
    dw.setLegend(name);

    if (dw.exec() == QDialog::Accepted)
    {
      DataFilters filters;

      if (dw.getLeftSplitter() > dist.minBound())
      {
        DataFilters::DataFilter filter;
        filter.value = dw.getLeftSplitter();
        filter.field = DataFilters::META_DATA;
        filter.meta_name = name;
        filter.op = DataFilters::GREATER_EQUAL;
        filter.value_is_numerical = true;
        filters.add(filter);
      }

      if (dw.getRightSplitter() < dist.maxBound())
      {
        DataFilters::DataFilter filter;
        filter.value = dw.getRightSplitter();
        filter.field = DataFilters::META_DATA;
        filter.meta_name = name;
        filter.op = DataFilters::LESS_EQUAL;
        filter.value_is_numerical = true;
        filters.add(filter);
      }

      canvas_->setFilters(filters);
    }
  }
Ejemplo n.º 7
0
  void SpectrumWidget::showIntensityDistribution()
  {
    Histogram<> dist = createIntensityDistribution_();
    HistogramDialog dw(dist);
    dw.setLegend("intensity");
    dw.setLogMode(true);
    if (dw.exec() == QDialog::Accepted)
    {
      DataFilters filters;

      if (dw.getLeftSplitter() > dist.minBound())
      {
        DataFilters::DataFilter filter;
        filter.value = dw.getLeftSplitter();
        filter.field = DataFilters::INTENSITY;
        filter.op = DataFilters::GREATER_EQUAL;
        filters.add(filter);
      }

      if (dw.getRightSplitter() < dist.maxBound())
      {
        DataFilters::DataFilter filter;
        filter.value = dw.getRightSplitter();
        filter.field = DataFilters::INTENSITY;
        filter.op = DataFilters::LESS_EQUAL;
        filters.add(filter);
      }

      canvas_->setFilters(filters);
    }
  }
Ejemplo n.º 8
0
    /**
     * Compute the histogram of distances between sample points on the shape. The histogram bins uniformly subdivide the range
     * of distances from zero to \a max_distance. If \a max_distance is negative, the shape scale specified in the constructor
     * will be used.
     *
     * @param histogram The histogram to be computed.
     * @param dist_type The type of distance metric.
     * @param max_distance The maximum separation between points to consider for the histogram. A negative value indicates the
     *   entire shape is to be considered (in which case \a max_distance is set to the shape scale specified in the
     *   constructor). The histogram range is set appropriately.
     * @param pair_reduction_ratio The fraction of the available set of point pairs -- expressed as a number between 0 and 1 --
     *   that will be randomly selected and used to actually build the histogram. Note that the final set is a subsampling of
     *   the set of all possible pairs, not the set of all possible pairs of a subsampled set of points. This may be useful for
     *   getting a more evenly sampled set of pairwise distances, with an extra-large initial set of points. A value of 1
     *   indicates all ordered pairs will be used, but this counts every distance twice, so a value of 0.5 or so may be more
     *   appropriate. A negative value picks a default of 0.5, or the ratio that gives a maximum of ~1M ordered pairs, whichever
     *   is smaller.
     */
    void compute(Histogram & histogram, DistanceType dist_type, Real max_distance = -1, Real pair_reduction_ratio = -1) const
    {
      long num_samples = ldh.numSamples();
      long num_distinct_unordered = (num_samples - 1) * num_samples;

      if (pair_reduction_ratio < 0)
        pair_reduction_ratio = (Real)std::min(0.5, 1000000.0 / num_distinct_unordered);  // don't count (x, x)

      histogram.setZero();  // don't bother setting the range

      Real local_reduction_ratio = std::sqrt(pair_reduction_ratio);
      long num_queries = Math::clamp((long)std::ceil(local_reduction_ratio * num_samples), 0, num_samples - 1);
      if (num_queries <= 0)
        return;

      TheaArray<int32> query_indices((array_size_t)num_queries);
      Random::common().sortedIntegers(0, (int32)num_samples - 1, (int32)num_queries, &query_indices[0]);

      Histogram local_histogram(histogram.numBins());
      for (array_size_t i = 0; i < query_indices.size(); ++i)
      {
        Vector3 p = ldh.getSamplePosition(query_indices[i]);
        ldh.compute(p, local_histogram, dist_type, max_distance, local_reduction_ratio);

        // Remove the zero distance from the query point to itself
        local_histogram.remove(0.0);

        if (i == 0)
          histogram.setRange(local_histogram.minValue(), local_histogram.maxValue());

        histogram.insert(local_histogram);
      }
    }
Ejemplo n.º 9
0
NS_IMETHODIMP
TelemetryImpl::GetHistogramSnapshots(JSContext *cx, jsval *ret)
{
  JSObject *root_obj = JS_NewObject(cx, NULL, NULL, NULL);
  if (!root_obj)
    return NS_ERROR_FAILURE;
  *ret = OBJECT_TO_JSVAL(root_obj);

  StatisticsRecorder::Histograms h;
  StatisticsRecorder::GetHistograms(&h);
  for (StatisticsRecorder::Histograms::iterator it = h.begin(); it != h.end();++it) {
    Histogram *h = *it;
    JSObject *hobj = JS_NewObject(cx, NULL, NULL, NULL);
    if (!(hobj
          && JS_DefineProperty(cx, root_obj, h->histogram_name().c_str(),
                               OBJECT_TO_JSVAL(hobj), NULL, NULL, JSPROP_ENUMERATE)
          && ReflectHistogramSnapshot(cx, hobj, h))) {
      return NS_ERROR_FAILURE;
    }
  }

  MutexAutoLock hashMutex(mHashMutex);
  // Add info about slow SQL queries on the main thread
  if (!AddSlowSQLInfo(cx, root_obj, true))
    return NS_ERROR_FAILURE;
  // Add info about slow SQL queries on other threads
  if (!AddSlowSQLInfo(cx, root_obj, false))
    return NS_ERROR_FAILURE;

  return NS_OK;
}
Ejemplo n.º 10
0
    /**
     * Compute the histogram of euclidean distances from a query point to sample points on the shape. The histogram bins
     * uniformly subdivide the range of distances from zero to \a max_distance. If \a max_distance is negative, the shape scale
     * specified in the constructor will be used.
     *
     * @param position The position of the query point.
     * @param histogram The histogram to be computed.
     * @param max_distance The distance to the furthest point to consider for the histogram. A negative value indicates the
     *   entire shape is to be considered (in which case \a max_distance is set to the shape scale specified in the
     *   constructor). The histogram range is set appropriately.
     * @param sample_reduction_ratio The fraction of the available set of samples -- expressed as a number between 0 and 1 --
     *   that will be randomly selected and used to actually build the histogram. This may be useful for getting a more evenly
     *   sampled set of pairwise distances when calling this function with multiple query points (and an extra-large initial set
     *   of points). A negative value, or a value of 1, indicates all sample points will be used.
     */
    void computeGeodesic(Vector3 const & position, Histogram & histogram, Real max_distance, Real sample_reduction_ratio) const
    {
        if (sample_reduction_ratio < 0)
            sample_reduction_ratio = 1.1;  // play safe

        bool process_all = (max_distance < 0);
        if (process_all)
            max_distance = this->getNormalizationScale();

        histogram.setRange(0, std::max((double)max_distance, 1.0e-30));
        histogram.setZero();

        SampleGraph * graph = const_cast<SampleGraph *>(this->getSampleGraph());
        alwaysAssertM(graph, "LocalDistanceHistogram: Non-null sample graph required to compute geodesic distances");

        // Find the sample closest to the query position and use it as the source for all distance calculations
        long seed_index = -1;
        if (this->hasExternalKDTree())
            seed_index = this->getMutableExternalKDTree()->template closestElement<MetricL2>(position);
        else
            seed_index = this->getMutableInternalKDTree()->template closestElement<MetricL2>(position);

        alwaysAssertM(seed_index >= 0, "LocalDistanceHistogram: Seed sample for geodesic distances not found");

        // Assume the graph and the kd-tree have samples in the same sequence
        SampleGraph::SurfaceSample * seed_sample = const_cast<SampleGraph::SurfaceSample *>(&graph->getSample(seed_index));

        ShortestPaths<SampleGraph> shortest_paths;
        GeodesicCallback callback(histogram, sample_reduction_ratio);
        shortest_paths.dijkstraWithCallback(*graph, seed_sample, &callback, (process_all ? -1 : max_distance));
    }
Ejemplo n.º 11
0
void VectorTest::test_calculate_bin(void)
{
    message += "test_calculate_bin\n";

    Vector<double> v;

    size_t bin;

    Histogram<double> histogram;

    v.set(0.0, 1.0, 9.0);

    histogram = v.calculate_histogram(10);

    // Test

    bin = histogram.calculate_bin(v[0]);

    assert_true(bin == 0, LOG);

    // Test

    bin = histogram.calculate_bin(v[1]);

    assert_true(bin == 1, LOG);

    // Test

    bin = histogram.calculate_bin(v[2]);

    assert_true(bin == 2, LOG);
}
Ejemplo n.º 12
0
    /**
     * Compute the histogram of euclidean distances from a query point to sample points on the shape. The histogram bins
     * uniformly subdivide the range of distances from zero to \a max_distance. If \a max_distance is negative, the shape scale
     * specified in the constructor will be used.
     *
     * @param position The position of the query point.
     * @param histogram The histogram to be computed.
     * @param max_distance The distance to the furthest point to consider for the histogram. A negative value indicates the
     *   entire shape is to be considered (in which case \a max_distance is set to the shape scale specified in the
     *   constructor). The histogram range is set appropriately.
     * @param sample_reduction_ratio The fraction of the available set of samples -- expressed as a number between 0 and 1 --
     *   that will be randomly selected and used to actually build the histogram. This may be useful for getting a more evenly
     *   sampled set of pairwise distances when calling this function with multiple query points (and an extra-large initial set
     *   of points). A negative value, or a value of 1, indicates all sample points will be used.
     */
    void computeEuclidean(Vector3 const & position, Histogram & histogram, Real max_distance, Real sample_reduction_ratio) const
    {
        if (sample_reduction_ratio < 0)
            sample_reduction_ratio = 1.1;  // play safe

        bool process_all = (max_distance < 0);
        if (process_all)
            max_distance = this->getNormalizationScale();

        histogram.setRange(0, std::max((double)max_distance, 1.0e-30));
        histogram.setZero();

        EuclideanCallback callback(position, histogram, sample_reduction_ratio);

        if (process_all)
        {
            long num_samples = this->numSamples();
            for (long i = 0; i < num_samples; ++i)
                callback(i, this->getSamplePosition(i));
        }
        else
        {
            Ball3 ball(position, max_distance);

            if (this->hasExternalKDTree())
                this->getMutableExternalKDTree()->template processRangeUntil<IntersectionTester>(ball, &callback);
            else
                this->getMutableInternalKDTree()->template processRangeUntil<IntersectionTester>(ball, &callback);
        }
    }
Ejemplo n.º 13
0
void Application::computeRatios(const BOOM::String &filestem,
				Histogram<double> &posHist,
				Histogram<double> &backgroundHist,
				double minScore,
				double maxScore,int numBins)
{
  BOOM::String outfile=filestem+".isp";
  ofstream os(outfile.c_str());
  double binSize=(maxScore-minScore)/numBins;
  os<<minScore<<"\t"<<maxScore<<"\t"<<numBins<<"\t"<<binSize<<endl;
  double sum=posHist.sum();
  for(int i=0 ; i<numBins ; ++i)
    {
      double x=minScore+i*binSize;
      //double numerator=posHist.getBin(i);
      //double denominator=backgroundHist.getBin(i);
      double numerator=posHist.getBin(i)/sum;
      //(posHist.getBin(i)+backgroundHist.getBin(i));
      double denominator=1-numerator;
      double r=denominator ? numerator/denominator : 1;
      //os<<x<<"\t"<<r<<"\t"<<posHist.getBin(i)<<"\t"<<backgroundHist.getBin(i)<<endl;
      os<<x<<"\t"<<(x+binSize)<<"\t"<<log(r)<<endl;
    }
  cout<<"Ratios written into "<<outfile<<endl;
}
Ejemplo n.º 14
0
TEST(Histogram, testBinarization)
{
    G12Buffer *image = BufferFactory::getInstance()->loadG12Bitmap("data/pair/image0001_c0.pgm");
    CORE_ASSERT_TRUE(image != NULL, "missed testBinarization input data");

    Histogram *histogram = new Histogram(image);

    int meanLevel   = histogram->getMeanThreshold();
    int medianLevel = histogram->getMedianThreshold();
    int otsuLevel   = histogram->getOtsuThreshold();

    G12Buffer *meanImage   = image->binarize(meanLevel);
    BMPLoader().save("mean.bmp", meanImage);

    G12Buffer *medianImage = image->binarize(medianLevel);
    BMPLoader().save("median.bmp", medianImage);

    G12Buffer *otsuImage   = image->binarize(otsuLevel);
    BMPLoader().save("otsu.bmp", otsuImage);

    delete otsuImage;
    delete medianImage;
    delete meanImage;
    delete histogram;
    delete image;
}
Ejemplo n.º 15
0
Histogram<DIM, POS, VAL>::Histogram(const Histogram<DIM, POS, VAL>& histo)
	: Array<DIM, VAL>(histo)
{
	m_spaceMin = histo.getMinPosition();
	m_spaceMax = histo.getMaxPosition();
	m_spaceSize = m_spaceMax - m_spaceMin;
}
Ejemplo n.º 16
0
Archivo: Main.cpp Proyecto: vt1/Cpp
int main()
{
	int sizeArr;
	cout << "enter array size: " << endl;
	cin >> sizeArr;
	Histogram *pMyHistogram = new Histogram(sizeArr);	
	pMyHistogram->showHistogram(sizeArr);
}
Ejemplo n.º 17
0
/**
 * Performs cubic spline interpolation from input to output
 * @param input A histogram from which to interpolate
 * @param output A histogram where to store the interpolated values
 */
void interpolateCSplineInplace(const Histogram &input, Histogram &output) {
  sanityCheck(input, output, minSizeForCSplineInterpolation());
  const auto &points = input.points().rawData();
  const auto &y = input.y().rawData();
  const auto &interpPoints = output.points();
  auto &newY = output.mutableY();
  interpolateInplace(points, y, interpPoints, newY, InterpolationType::CSPLINE);
}
  Histogram<> Spectrum1DWidget::createMetaDistribution_(const String& name) const
  {
    Histogram<> tmp;
    //float arrays
    const ExperimentType::SpectrumType::FloatDataArrays& f_arrays = (*canvas_->getCurrentLayer().getPeakData())[0].getFloatDataArrays();
    for (ExperimentType::SpectrumType::FloatDataArrays::const_iterator it = f_arrays.begin(); it != f_arrays.end(); ++it)
    {
      if (it->getName() == name)
      {
        //determine min and max of the data
        float min = numeric_limits<float>::max(), max = -numeric_limits<float>::max();
        for (Size i = 0; i < it->size(); ++i)
        {
          if ((*it)[i] < min)
            min = (*it)[i];
          if ((*it)[i] > max)
            max = (*it)[i];
        }
        if (min >= max)
          return tmp;

        //create histogram
        tmp.reset(min, max, (max - min) / 500.0);
        for (Size i = 0; i < it->size(); ++i)
        {
          tmp.inc((*it)[i]);
        }
      }
    }
    //integer arrays
    const ExperimentType::SpectrumType::IntegerDataArrays& i_arrays = (*canvas_->getCurrentLayer().getPeakData())[0].getIntegerDataArrays();
    for (ExperimentType::SpectrumType::IntegerDataArrays::const_iterator it = i_arrays.begin(); it != i_arrays.end(); ++it)
    {
      if (it->getName() == name)
      {
        //determine min and max of the data
        float min = numeric_limits<float>::max(), max = -numeric_limits<float>::max();
        for (Size i = 0; i < it->size(); ++i)
        {
          if ((*it)[i] < min)
            min = (*it)[i];
          if ((*it)[i] > max)
            max = (*it)[i];
        }
        if (min >= max)
          return tmp;

        //create histogram
        tmp.reset(min, max, (max - min) / 500.0);
        for (Size i = 0; i < it->size(); ++i)
        {
          tmp.inc((*it)[i]);
        }
      }
    }
    //fallback if no array with that name exists
    return tmp;
  }
Ejemplo n.º 19
0
NS_IMETHODIMP
TelemetryImpl::GetHistogramSnapshots(JSContext *cx, jsval *ret)
{
  JSObject *root_obj = JS_NewObject(cx, NULL, NULL, NULL);
  if (!root_obj)
    return NS_ERROR_FAILURE;
  *ret = OBJECT_TO_JSVAL(root_obj);

  // Ensure that all the HISTOGRAM_FLAG histograms have been created, so
  // that their values are snapshotted.
  for (size_t i = 0; i < Telemetry::HistogramCount; ++i) {
    if (gHistograms[i].histogramType == nsITelemetry::HISTOGRAM_FLAG) {
      Histogram *h;
      DebugOnly<nsresult> rv = GetHistogramByEnumId(Telemetry::ID(i), &h);
      MOZ_ASSERT(NS_SUCCEEDED(rv));
    }
  };

  StatisticsRecorder::Histograms hs;
  StatisticsRecorder::GetHistograms(&hs);

  // We identify corrupt histograms first, rather than interspersing it
  // in the loop below, to ensure that our corruption statistics don't
  // depend on histogram enumeration order.
  //
  // Of course, we hope that all of these corruption-statistics
  // histograms are not themselves corrupt...
  IdentifyCorruptHistograms(hs);

  // OK, now we can actually reflect things.
  for (HistogramIterator it = hs.begin(); it != hs.end(); ++it) {
    Histogram *h = *it;
    if (!ShouldReflectHistogram(h) || IsEmpty(h)) {
      continue;
    }

    JSObject *hobj = JS_NewObject(cx, NULL, NULL, NULL);
    if (!hobj) {
      return NS_ERROR_FAILURE;
    }
    JS::AutoObjectRooter root(cx, hobj);
    switch (ReflectHistogramSnapshot(cx, hobj, h)) {
    case REFLECT_CORRUPT:
      // We can still hit this case even if ShouldReflectHistograms
      // returns true.  The histogram lies outside of our control
      // somehow; just skip it.
      continue;
    case REFLECT_FAILURE:
      return NS_ERROR_FAILURE;
    case REFLECT_OK:
      if (!JS_DefineProperty(cx, root_obj, h->histogram_name().c_str(),
                             OBJECT_TO_JSVAL(hobj), NULL, NULL, JSPROP_ENUMERATE)) {
        return NS_ERROR_FAILURE;
      }
    }
  }
  return NS_OK;
}
Ejemplo n.º 20
0
void theta::randomize_poisson(Histogram & h, Random & rnd){
    const size_t nbins = h.get_nbins();
    for(size_t bin=0; bin<=nbins+1; ++bin){
        double mu = h.get(bin);
        if(mu > 0.){
            h.set(bin, rnd.poisson(mu));
        }
    }
}
Ejemplo n.º 21
0
void estimatePolynomial(const size_t order, const Histogram &histo,
                        const size_t i_min, const size_t i_max, double &out_bg0,
                        double &out_bg1, double &out_bg2,
                        double &out_chisq_red) {
  const auto &X = histo.points();
  const auto &Y = histo.y();
  estimate(order, X, Y, i_min, i_max, 0, 0, false, out_bg0, out_bg1, out_bg2,
           out_chisq_red);
}
// ######################################################################
void CenterSurroundHistogramSegmenter::csTemplateSalientRegion
(Point2D<int> pt)
{
  Point2D<int> gpt(pt.i/GRID_SIZE, pt.j/GRID_SIZE);

  Rectangle intRect = itsIntegralHistogram.getBounds();

  Timer tim(1000000); tim.reset();

  // try the various center surround combination
  for(uint i = 0; i < itsCStemplates.size(); i++)
    {
      Rectangle cR = itsCStemplates[i].first;
      Rectangle sR = itsCStemplates[i].second;

      // only use the rectangle part that overlaps the image
      Rectangle grC = intRect.getOverlap(cR+gpt);
      Rectangle grS = intRect.getOverlap(sR+gpt);
  
      // get the center and surround histograms
      rutz::shared_ptr<Histogram> hC  = getGridHistogramDistribution(grC);
      rutz::shared_ptr<Histogram> hCS = getGridHistogramDistribution(grS);
      Histogram hS = (*hCS) - (*hC);

      // smooth and normalize
      int npointC = grC.area()*GRID_SIZE*GRID_SIZE;
      int npointS = grS.area()*GRID_SIZE*GRID_SIZE - npointC;
      Histogram shC = smoothAndNormalize(*hC, npointC);
      Histogram shS = smoothAndNormalize( hS, npointS);

      // get the difference
      float diff = shS.getChiSqDiff(shC);      

      // update the center surround belief estimation
      // we store the max as the best estimation of belief
      for(int ii = grS.left(); ii <= grS.rightI(); ii++)
        for(int jj = grS.top(); jj <= grS.bottomI(); jj++)
          {
            Point2D<int> pt(ii,jj);

            // if point is in center 
            if(grC.contains(pt))
              {
                float prevC = itsGridCenterBelief.getVal(ii,jj);
                if(prevC < diff) itsGridCenterBelief.setVal(ii,jj, diff);
              }
            // or surround
            else
              {
                float prevS = itsGridSurroundBelief.getVal(ii,jj);
                if(prevS < diff) itsGridSurroundBelief.setVal(ii,jj, diff);
              }
          }
    }

  LINFO("time: %f", tim.get()/1000.0F);
}
Ejemplo n.º 23
0
void VectorTest::test_calculate_histogram(void)
{
   message += "test_calculate_histogram\n";

   Vector<double> v;

   Histogram<double> histogram;

   Vector<double> centers;
   Vector<size_t> frequencies;

   // Test

   v.set(0.0, 1.0, 9.0);

   histogram = v.calculate_histogram(10); 

   assert_true(histogram.get_bins_number() == 10, LOG);

   centers = histogram.centers;
   frequencies = histogram.frequencies;
                                        
   assert_true(fabs(centers[0] - 0.45) < 1.0e-12, LOG);
   assert_true(fabs(centers[1] - 1.35) < 1.0e-12, LOG);
   assert_true(fabs(centers[2] - 2.25) < 1.0e-12, LOG);
   assert_true(fabs(centers[3] - 3.15) < 1.0e-12, LOG);
   assert_true(fabs(centers[4] - 4.05) < 1.0e-12, LOG);
   assert_true(fabs(centers[5] - 4.95) < 1.0e-12, LOG);
   assert_true(fabs(centers[6] - 5.85) < 1.0e-12, LOG);
   assert_true(fabs(centers[7] - 6.75) < 1.0e-12, LOG);
   assert_true(fabs(centers[8] - 7.65) < 1.0e-12, LOG);
   assert_true(fabs(centers[9] - 8.55) < 1.0e-12, LOG);

   assert_true(frequencies[0] == 1, LOG);
   assert_true(frequencies[1] == 1, LOG);
   assert_true(frequencies[2] == 1, LOG);
   assert_true(frequencies[3] == 1, LOG);
   assert_true(frequencies[4] == 1, LOG);
   assert_true(frequencies[5] == 1, LOG);
   assert_true(frequencies[6] == 1, LOG);
   assert_true(frequencies[7] == 1, LOG);
   assert_true(frequencies[8] == 1, LOG);
   assert_true(frequencies[9] == 1, LOG);
   assert_true(histogram.frequencies.calculate_sum() == 10, LOG);

   // Test

   v.set(20);
   v.randomize_normal();

   histogram = v.calculate_histogram(10);

   assert_true(histogram.frequencies.calculate_sum() == 20, LOG);


}
Ejemplo n.º 24
0
NS_IMETHODIMP
TelemetryImpl::NewHistogram(const nsACString &name, uint32_t min, uint32_t max, uint32_t bucketCount, uint32_t histogramType, JSContext *cx, jsval *ret)
{
  Histogram *h;
  nsresult rv = HistogramGet(PromiseFlatCString(name).get(), min, max, bucketCount, histogramType, &h);
  if (NS_FAILED(rv))
    return rv;
  h->ClearFlags(Histogram::kUmaTargetedHistogramFlag);
  return WrapAndReturnHistogram(h, cx, ret);
}
void COpenCVInterfaceDlg::OnToolsHistogram()
{
	if(mainImage.cols)
	{
		Histogram dlg;
		dlg.setHisto(Tools::calcHisto(mainImage));
		dlg.DoModal();
	}
	else
		MessageBox("No image loaded");
}
Ejemplo n.º 26
0
/** Return the most likely distance between two contigs and the number
 * of pairs that support that estimate. */
static pair<int, unsigned>
maximumLikelihoodEstimate(int first, int last,
		const Histogram& samples,
		const PMF& pmf,
		unsigned len0, unsigned len1)
{
	int filterSize = 2 * (int)(0.05 * pmf.mean()) + 3; // want an odd filter size
	first = max(first, (int)pmf.minValue() - samples.maximum()) - filterSize/2;
	last = min(last, (int)pmf.maxValue() - samples.minimum()) + filterSize/2 + 1;

	/* When randomly selecting fragments that span a given point,
	 * longer fragments are more likely to be selected than
	 * shorter fragments.
	 */
	WindowFunction window(len0, len1);

	unsigned nsamples = samples.size();
	double bestLikelihood = -numeric_limits<double>::max();
	int bestTheta = first;
	unsigned bestn = 0;
	vector<double> le;
	vector<unsigned> le_n;
	vector<int> le_theta;
	for (int theta = first; theta <= last; theta++) {
		// Calculate the normalizing constant of the PMF, f_theta(x).
		double c = 0;
		for (int i = pmf.minValue(); i <= (int)pmf.maxValue(); ++i)
			c += pmf[i] * window(i - theta);

		double likelihood;
		unsigned n;
	   	tie(likelihood, n) = computeLikelihood(theta, samples, pmf);
		likelihood -= nsamples * log(c);
		le.push_back(likelihood);
		le_n.push_back(n);
		le_theta.push_back(theta);
	}

	HannWindow filter(filterSize);
	for (int i = filterSize / 2; i < (int)le.size()-(filterSize / 2); i++) {
		double likelihood = 0;
		for (int j = -filterSize / 2; j <= filterSize / 2; j++) {
			assert((unsigned)(i + j) < le.size() && i + j >= 0);
			likelihood += filter(j) * le[i + j];
		}

		if (le_n[i] > 0 && likelihood > bestLikelihood) {
			bestLikelihood = likelihood;
			bestTheta = le_theta[i];
			bestn = le_n[i];
		}
	}
	return make_pair(bestTheta, bestn);
}
Ejemplo n.º 27
0
cv::Mat ExtractContours::Binarization(cv::Mat image, cv::Mat result)
{
	cv::Mat imageGray = image.clone();
	cv::cvtColor(image, imageGray, cv::COLOR_BGR2GRAY);
	cv::bilateralFilter(imageGray, result, 0, 10, 10);
	Histogram histo;
	int nr = histo.Thresh(imageGray);
	//histograma -> pragul pica unde se termina gausianul
	cv::threshold(imageGray, result, nr, 255, CV_ADAPTIVE_THRESH_MEAN_C);
	return result;
}
Ejemplo n.º 28
0
void estimateBackground(const size_t order, const Histogram &histo,
                        const size_t i_min, const size_t i_max,
                        const size_t p_min, const size_t p_max, double &out_bg0,
                        double &out_bg1, double &out_bg2,
                        double &out_chisq_red) {
  const auto &X = histo.points();
  const auto &Y = histo.y();

  // fit with a hole in the middle
  estimate(order, X, Y, i_min, i_max, p_min, p_max, true, out_bg0, out_bg1,
           out_bg2, out_chisq_red);
}
Ejemplo n.º 29
0
void Histogram<DIM, POS, VAL>::operator-=(const Histogram<DIM, POS, VAL>& i_histo)
{
	if(i_histo.getSize() != this->getSize())
	{
		throw exception::Message("Histogram::operator+= wrong size", STK_DBG_INFO);
	}
	
	for(int i=0; i<this->getArraySize(); i++)
	{
		this->getFromIndice(i) -= i_histo.getFromIndice(i);
	}
}
Ejemplo n.º 30
0
JSBool
JSHistogram_Clear(JSContext *cx, unsigned argc, jsval *vp)
{
  JSObject *obj = JS_THIS_OBJECT(cx, vp);
  if (!obj) {
    return JS_FALSE;
  }

  Histogram *h = static_cast<Histogram*>(JS_GetPrivate(obj));
  h->Clear();
  return JS_TRUE;
}