Ejemplo n.º 1
0
//------------------ shows histogram values on the graphic----------------------------------
void MainWindow::on_pushButton_clicked()
{
    Histogram1D graph;

    cv::namedWindow("histogram graph");
    cv::imshow("histogram graph", graph.getHistogramImage(image));
}
Ejemplo n.º 2
0
//----------------- shows image's histogram on terminal-----------------------------------
void MainWindow::on_pushButton_2_clicked()
{
    Histogram1D terminal;

    cv::MatND histo=terminal.getHistogram(image);
// shows values of histgoram on terminal
   for (int i=0; i<256; i++)
        std::cout<<"value"<<i<<"="<<histo.at<float>(i)<<std::endl;
}
Ejemplo n.º 3
0
void case2histogram() {
    cv::Mat image=cv::imread( inputImagePath4case1histogram,cv::IMREAD_GRAYSCALE );//open in b&w
    alert_win( image );

    Histogram1D h;
    cv::Mat re= h.getHistogramImage(image);
    alert_win( re );

}
Ejemplo n.º 4
0
void case1histogram() {
    cv::Mat image=cv::imread( inputImagePath4case1histogram,cv::IMREAD_GRAYSCALE );//open in b&w
    Histogram1D h;
    cv::MatND histo=h.getHistogram(image);

    for(int i=0; i<256; i++) {
        cout<<"Value "<< i << " = " << histo.at<float>( i )<<endl;
    }
}
Ejemplo n.º 5
0
void case4histogram() {
    cv::Mat image=cv::imread( inputImagePath4case1histogram,cv::IMREAD_GRAYSCALE );
    alert_win( image );

    Histogram1D h;
    cv::Mat eq=h.equalize( image );
    alert_win( eq );

}
Ejemplo n.º 6
0
//-------------------- equalized the b&w image -------------------------------------------------
//---------------------- shows it's histogram values on a graph --------------------------------
void MainWindow::on_pushButton_6_clicked()
{
    Histogram1D equa;

    cv::namedWindow("equalized");
    cv::namedWindow("equalized histogram");

    cv::Mat equalized=equa.equalize(image);
    cv::imshow("equalized",equalized);
    cv::imshow("equalized histogram",equa.getHistogramImage(equalized));

}
Ejemplo n.º 7
0
void Histogram1D::multiply_with_ratio_exponented(const Histogram1D & nominator, const Histogram1D & denominator, double exponent){
   check_compatibility(nominator);
   check_compatibility(denominator);
   const double * n_data = nominator.get_data();
   const double * d_data = denominator.get_data();
   double * data = get_data();
   const size_t n = size();
   for(size_t i=0; i<n; i++){
      if(d_data[i]>0.0)
         data[i] *= pow(n_data[i] / d_data[i], exponent);
   }
}
Ejemplo n.º 8
0
void ImagePro::on_btnEqualizer_clicked()
{
    cv::Mat tepImg;
    std::vector<cv::Mat> tmp;
    cv::split(_img,tmp);
    Histogram1D HH;
    for (int i=0;i<3;i++){
        tmp[i]=HH.equalize(tmp[i]);
    }
    cv::merge(tmp,tepImg);
    cv::namedWindow("histogram equalize");
    cv::imshow("histogram equalize",tepImg);
}
Ejemplo n.º 9
0
void ImagePro::on_btnHistoStretch_clicked()
{
    cv::Mat tepImg;
    std::vector<cv::Mat> tmp;
    cv::split(_img,tmp);
    Histogram1D HH;
    for (int i=0;i<3;i++){
        tmp[i]=HH.stretch(tmp[i]);
    }
    cv::merge(tmp,tepImg);
    cv::namedWindow("stretch histogram");
    cv::imshow("stretch histogram",tepImg);
}
Ejemplo n.º 10
0
bool histos_equal(const Histogram1D & h1, const Histogram1D & h2){
    if(h1.get_nbins()!=h2.get_nbins()) return false;
    if(h1.get_xmin()!=h2.get_xmin()) return false;
    if(h1.get_xmax()!=h2.get_xmax()) return false;
    const size_t n = h1.get_nbins();
    for(size_t i=0; i<n; i++){
        if(h1.get(i)!=h2.get(i)) return false;
    }
    return true;
}
Ejemplo n.º 11
0
//---------------------------stretches the image on some level---------------------------------------
//--------------------------- and also show it's histogram level on a grahp--------------------------
void MainWindow::on_pushButton_5_clicked()
{
    Histogram1D str;

    cv::Mat strecthLevel;

    cv::namedWindow("stretched");
    int x= ui->lineEdit->text().toInt();


    cv::Mat strecthed = str.strecth(image,x);
    cv::imshow("stretched", strecthed);
    cv::imshow("stretched histogram",str.getHistogramImage(strecthed));
}
Ejemplo n.º 12
0
void Histogram1D::fail_check_compatibility(const Histogram1D & h) const {
    std::stringstream s;
    s <<  "Histogram1D::check_compatibility: Histograms are not compatible (nbins, xmin, xmax) are: "
            " (" << get_nbins() << ", " << xmin << ", " << xmax << ") and "
            " (" << h.get_nbins() << ", " << h.xmin << ", " << h.xmax << ")";
    throw invalid_argument(s.str());
}
Ejemplo n.º 13
0
cv::Mat ImageProcessor::simplifyImage(cv::Mat &origImage, int blurWindow, int stretchMinVal, int equalize) {
	cv::Mat improvImage;
	Histogram1D h;

	if(origImage.type() != 0) cv::cvtColor( origImage, improvImage, CV_BGR2GRAY );
	else origImage.copyTo(improvImage);

	if (equalize) {
		cv::equalizeHist(improvImage, improvImage);
	} else {
		improvImage = h.stretch(improvImage, stretchMinVal);
	}

	if(blurWindow > 0)
		cv::medianBlur(improvImage, improvImage, blurWindow);

	return improvImage;
}
Ejemplo n.º 14
0
void Histogram1D::operator*=(const Histogram1D & h) {
    check_compatibility(h);
    const double * hdata = h.get_data();
    double * data = get_data();
    const size_t n = size();
    for (size_t i = 0; i < n; ++i) {
        data[i] *= hdata[i];
    }
}
Ejemplo n.º 15
0
//-------------------- tranforms the image to negative---------------------------------------
//-------------------- shows it's histogram values on graphic--------------------------------
void MainWindow::on_pushButton_4_clicked()
{
    Histogram1D negative;
    //build look up
    int dim(256);
    cv::Mat lut(1, &dim, CV_8U); // lut is a matrix which is in 1D
    for(int i=0; i<256; i++)
    {
        lut.at<uchar>(i)=255-i; //takes all the values and reverses it
    }
    cv::Mat negativeResult;
    negativeResult=negative.applyLookUp(image,lut);
    cv::namedWindow("negative");
    cv::imshow("negative",negativeResult);

    //negative image histogram
    cv::imshow("negative histogram",negative.getHistogramImage(negativeResult));

}
Ejemplo n.º 16
0
int main()
{
  Mat src;
  src = imread("box.png");
 if( !src.data )
    { 
  cout<<"error";
  }

  namedWindow("image", CV_WINDOW_AUTOSIZE );
  imshow("image", src );
  waitKey(0);

  // The histogram object
Histogram1D h;
namedWindow("Histogram");
imshow("Histogram",h.getHistogramImage(src));
waitKey(0);

  return 1;

}
Ejemplo n.º 17
0
void ImagePro::on_btnLoadImg_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
                                                    tr("Open Image"), ".",
                                                    tr("Image Files (*.png *.jpg *.jpeg *.bmp)"));

    _img= cv::imread(fileName.toUtf8().constData());
    cv::namedWindow("Original Image");
    cv::imshow("Original Image", _img);

    Histogram1D HH;
    cv::Mat histIm = HH.getHistgramImage(_img);
    cv::namedWindow("Histogram");
    cv::imshow("Histogram", histIm);

    cv::Mat thresholded;
    cv::Mat imgG;
    cv::cvtColor(_img,imgG,CV_BGR2GRAY);
    cv::threshold(imgG,thresholded,60,255,cv::THRESH_BINARY);
    cv::namedWindow("binary");
    cv::imshow("binary", thresholded);

}
Ejemplo n.º 18
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Mat image = imread("D:\\workspace\\pictures\\771413900_m.jpg",0);
    Mat thresholded, result;

    Histogram1D h;

    MatND histo = h.getHistogram(image);

    for (int i=0;i<256;i++)
        cout << "Value" << i << "=" << histo.at<float>(i) << endl;

    imshow("Orginal", image);

    imshow("Histogram",h.getHistogramImage(image));

    //threshold(image, thresholded,128,255,THRESH_BINARY);

    //imshow("Threshold",thresholded);

    equalizeHist(image,result);

    //Mat stretched = h.stretch(image,100);

    //imshow("Stretched",stretched);

    imshow("Equalize",result);

    imshow("After Equalize Histogram",h.getHistogramImage(result));


    waitKey(50000);

    return a.exec();
}
Ejemplo n.º 19
0
// Split several histograms within the indexes l0 and lF so that
// the entropy after division is maximized
int splitHistogramsUsingEntropy(const std::vector<Histogram1D> &hist,
                                size_t l0, size_t lF)
{
    // Number of classes
    int K = hist.size();

    // Set everything outside l0 and lF to zero, and make it a PDF
    std::vector<Histogram1D> histNorm;
    for (int k = 0; k < K; k++)
    {
        Histogram1D histaux = hist[k];
        for (size_t l = 0; l < XSIZE(histaux); l++)
            if (l < l0 || l > lF)
                DIRECT_A1D_ELEM(histaux,l) = 0;
        histaux *= 1.0/histaux.sum();
        histNorm.push_back(histaux);
    }

    // Compute for each class the probability of being l<=l0 and l>l0
    MultidimArray<double> p(K, 2);
    for (int k = 0; k < K; k++)
    {
        const Histogram1D& histogram=histNorm[k];
        DIRECT_A2D_ELEM(p,k, 0) = DIRECT_A1D_ELEM(histogram,l0);
        DIRECT_A2D_ELEM(p,k, 1) = 0;
        for (size_t l = l0 + 1; l <= lF; l++)
            DIRECT_A2D_ELEM(p,k, 1) += DIRECT_A1D_ELEM(histogram,l);
    }

    // Compute the splitting l giving maximum entropy
    double maxEntropy = 0;
    int lmaxEntropy = -1;
    size_t l = l0;
    while (l < lF)
    {
        // Compute the entropy of the classes if we split by l
        double entropy = 0;
        FOR_ALL_DIRECT_ELEMENTS_IN_MULTIDIMARRAY(p)
        {
            double aux=DIRECT_MULTIDIM_ELEM(p,n);
            if (aux != 0)
                entropy -= aux * log10(aux);
        }

#ifdef DEBUG_SPLITTING_USING_ENTROPY
        std::cout << "Splitting at "  << l << " entropy=" << entropy
        << std::endl;
#endif

        // Check if this is the maximum
        if (entropy > maxEntropy)
        {
            maxEntropy = entropy;
            lmaxEntropy = l;
        }

        // Move to next split point
        ++l;

        // Update probabilities of being l<=l0 and l>l0
        for (int k = 0; k < K; k++)
        {
            const Histogram1D& histogram=histNorm[k];
            double aux=DIRECT_A1D_ELEM(histogram,l);
            DIRECT_A2D_ELEM(p,k, 0) += aux;
            DIRECT_A2D_ELEM(p,k, 1) -= aux;
        }
    }

#ifdef DEBUG_SPLITTING_USING_ENTROPY
    std::cout << "Finally in l=[" << l0 << "," << lF
    << " Max Entropy:" << maxEntropy
    << " lmax=" << lmaxEntropy << std::endl;
#endif

    // If the point giving the maximum entropy is too much on the extreme,
    // substitute it by the middle point
    if (lmaxEntropy<=2 || lmaxEntropy>=(int)lF-2)
        lmaxEntropy = (int)ceil((lF + l0)/2.0);

    return lmaxEntropy;
}
Ejemplo n.º 20
0
int main()
{
	// Read input image
    cv::Mat image= cv::imread("waves.jpg",0);
	if (!image.data)
		return 0; 

	// define image ROI
	cv::Mat imageROI;
	imageROI= image(cv::Rect(216,33,24,30)); // Cloud region

	// Display reference patch
	cv::namedWindow("Reference");
	cv::imshow("Reference",imageROI);

	// Find histogram of reference
	Histogram1D h;
	cv::Mat hist= h.getHistogram(imageROI);
	cv::namedWindow("Reference Hist");
	cv::imshow("Reference Hist",h.getHistogramImage(imageROI));

	// Create the content finder
	ContentFinder finder;

	// set histogram to be back-projected
	finder.setHistogram(hist);
	finder.setThreshold(-1.0f);

	// Get back-projection
	cv::Mat result1;
	result1= finder.find(image);

	// Create negative image and display result
	cv::Mat tmp;
	result1.convertTo(tmp,CV_8U,-1.0,255.0);
	cv::namedWindow("Backprojection result");
	cv::imshow("Backprojection result",tmp);

	// Get binary back-projection
	finder.setThreshold(0.12f);
	result1= finder.find(image);

	// Draw a rectangle around the reference area
	cv::rectangle(image, cv::Rect(216, 33, 24, 30), cv::Scalar(0, 0, 0));

	// Display image
	cv::namedWindow("Image");
	cv::imshow("Image",image);

	// Display result
	cv::namedWindow("Detection Result");
	cv::imshow("Detection Result",result1);

	// Load color image
	ColorHistogram hc;
    cv::Mat color= cv::imread("waves.jpg");

	// extract region of interest
	imageROI= color(cv::Rect(0,0,100,45)); // blue sky area

	// Get 3D colour histogram (8 bins per channel)
	hc.setSize(8); // 8x8x8
	cv::Mat shist= hc.getHistogram(imageROI);

	// set histogram to be back-projected
	finder.setHistogram(shist);
	finder.setThreshold(0.05f);

	// Get back-projection of color histogram
	result1= finder.find(color);

	cv::namedWindow("Color Detection Result");
	cv::imshow("Color Detection Result",result1);

	// Second color image
	cv::Mat color2= cv::imread("dog.jpg");

	cv::namedWindow("Second Image");
	cv::imshow("Second Image",color2);

	// Get back-projection of color histogram
	cv::Mat result2= finder.find(color2);

	cv::namedWindow("Result color (2)");
	cv::imshow("Result color (2)",result2);

	// Get ab color histogram
	hc.setSize(256); // 256x256
	cv::Mat colorhist= hc.getabHistogram(imageROI);

	// display 2D histogram
	colorhist.convertTo(tmp,CV_8U,-1.0,255.0);
	cv::namedWindow("ab histogram");
	cv::imshow("ab histogram",tmp);

	// set histogram to be back-projected
	finder.setHistogram(colorhist);
	finder.setThreshold(0.05f);

	// Convert to Lab space
	cv::Mat lab;
	cv::cvtColor(color, lab, CV_BGR2Lab);

	// Get back-projection of ab histogram
	int ch[2]={1,2};
	result1= finder.find(lab,0,256.0f,ch);

	cv::namedWindow("Result ab (1)");
	cv::imshow("Result ab (1)",result1);

	// Second colour image
	cv::cvtColor(color2, lab, CV_BGR2Lab);

	// Get back-projection of ab histogram
	result2= finder.find(lab,0,256.0,ch);

	cv::namedWindow("Result ab (2)");
	cv::imshow("Result ab (2)",result2);

	// Draw a rectangle around the reference sky area
    cv::rectangle(color,cv::Rect(0,0,100,45),cv::Scalar(0,0,0));
	cv::namedWindow("Color Image");
	cv::imshow("Color Image",color);

	
	// Get Hue colour histogram
	hc.setSize(180); // 180 bins
	colorhist= hc.getHueHistogram(imageROI);

	// set histogram to be back-projected
	finder.setHistogram(colorhist);

	// Convert to HSV space
	cv::Mat hsv;
	cv::cvtColor(color, hsv, CV_BGR2HSV);

	// Get back-projection of hue histogram
	ch[0]=0;
	result1= finder.find(hsv,0.0f,180.0f,ch);

	cv::namedWindow("Result Hue (1)");
	cv::imshow("Result Hue (1)",result1);

	// Second colour image
	color2= cv::imread("dog.jpg");

	// Convert to HSV space
	cv::cvtColor(color2, hsv, CV_BGR2HSV);

	// Get back-projection of hue histogram
	result2= finder.find(hsv,0.0f,180.0f,ch);

	cv::namedWindow("Result Hue (2)");
	cv::imshow("Result Hue (2)",result2);

	cv::waitKey();
	return 0;
}
Ejemplo n.º 21
0
int main_his()
{
	// Read input image
	cv::Mat image= cv::imread("Koala.jpg",0);
	if (!image.data)
		return 0; 

    // Display the image
	cv::namedWindow("Image");
	cv::imshow("Image",image);

	// The histogram object
	Histogram1D h;

    // Compute the histogram
	cv::MatND histo= h.getHistogram(image);

	// Loop over each bin
	for (int i=0; i<256; i++) 
		cout << "Value " << i << " = " << histo.at<float>(i) << endl;  

	// Display a histogram as an image
	cv::namedWindow("Histogram");
	cv::imshow("Histogram",h.getHistogramImage(image));

	// creating a binary image by thresholding at the valley
	cv::Mat thresholded;
	cv::threshold(image,thresholded,60,255,cv::THRESH_BINARY);
 
	// Display the thresholded image
	cv::namedWindow("Binary Image");
	cv::imshow("Binary Image",thresholded);
	cv::imwrite("binary.bmp",thresholded);

	// Equalize the image
	cv::Mat eq= h.equalize(image);

	// Show the result
	cv::namedWindow("Equalized Image");
	cv::imshow("Equalized Image",eq);

	// Show the new histogram
	cv::namedWindow("Equalized Histogram");
	cv::imshow("Equalized Histogram",h.getHistogramImage(eq));

	// Stretch the image ignoring bins with less than 5 pixels
	cv::Mat str= h.stretch(image,5);

	// Show the result
	cv::namedWindow("Stretched Image");
	cv::imshow("Stretched Image",str);

	// Show the new histogram
	cv::namedWindow("Stretched Histogram");
	cv::imshow("Stretched Histogram",h.getHistogramImage(str));

	// Create an image inversion table
	//uchar lookup[256];

			// Create lookup table
		int dims[1]={256};
		cv::MatND lookup(1,dims,CV_8U);
				for (int i=0; i<256; i++) {
		 lookup.at<uchar>(i)=255-i;
		}


	// Apply lookup and display negative image
	cv::namedWindow("Negative image");
	cv::imshow("Negative image",h.applyLookUp(image,lookup));

	cv::waitKey();
	return 0;
}
Ejemplo n.º 22
0
/* Constructor ------------------------------------------------------------- */
LeafNode::LeafNode(const std::vector < MultidimArray<double> > &leafFeatures,
                   int discrete_levels)
{
    __discreteLevels = discrete_levels;
    K = leafFeatures.size();
    if (__discreteLevels==0)
    {
        // This is a dummy node for features that cannot classify
        MultidimArray<int> newBins(1);
        A1D_ELEM(newBins,0)=0;
        Histogram1D hist;
        hist.resize(1);
        A1D_ELEM(hist,0)=1;
        IrregularHistogram1D irregHist;
        for (int k=0; k<K; k++)
        {
            irregHist.init(hist, newBins);
            irregHist.selfNormalize();
            __leafPDF.push_back(irregHist);
        }
    }
    else
    {
        // Compute the minimum and maximum of each class
        double minval=0., maxval=0.;
        for(int k=0; k<K; k++)
        {
            double minvalk=0., maxvalk=0.;
            leafFeatures[k].computeDoubleMinMax(minvalk, maxvalk);
            if (k==0)
            {
                minval=minvalk;
                maxval=maxvalk;
            }
            else
            {
                minval=std::min(minval,minvalk);
                maxval=std::max(maxval,maxvalk);
            }
        }
        if (minval==maxval)
        {
            __discreteLevels=0;
            return;
        }

        // Compute the PDF of each class
        std::vector<Histogram1D> hist(K);
        for (int k=0; k<K; k++)
        {
            // There is variation of this feature for this class
            compute_hist(leafFeatures[k], hist[k], minval, maxval, 100);
            hist[k] += 1; // Apply Laplace correction
        }

        // Split the histograms into discrete_level (power of 2) bins
        std::queue< Matrix1D<int> > intervals, splittedIntervals;
        Matrix1D<int> limits(2);
        VECTOR_R2(limits,0,99);
        intervals.push(limits);
        int imax=ROUND(log2(__discreteLevels));
        for (int i=0; i<imax; i++)
        {
            // Split all the intervals in the queue
            while (!intervals.empty())
            {
                Matrix1D<int> currentInterval = intervals.front();
                intervals.pop();
                int lsplit = splitHistogramsUsingEntropy(hist,
                             currentInterval(0), currentInterval(1));
                VECTOR_R2(limits,currentInterval(0),lsplit);
                splittedIntervals.push(limits);
                VECTOR_R2(limits,lsplit+1, currentInterval(1));
                splittedIntervals.push(limits);
            }

            // Copy the splitted intervals to the interval list
            while (!splittedIntervals.empty())
            {
                intervals.push(splittedIntervals.front());
                splittedIntervals.pop();
            }
        }

        // Compute the bins of the split
        MultidimArray<int> newBins(__discreteLevels);
        imax=intervals.size();
        for (int i=0; i<imax; i++)
        {
            A1D_ELEM(newBins,i) = intervals.front()(1);
            intervals.pop();
        }

        // Compute now the irregular histograms
        IrregularHistogram1D irregHist;
        for (int k=0; k<K; k++)
        {
            irregHist.init(hist[k], newBins);
            irregHist.selfNormalize();
            __leafPDF.push_back(irregHist);
        }
    }
}
Ejemplo n.º 23
0
 //note: this is split into checking and reporting in another routine fail_check_compatibility
 // to increase inlining probability
 void check_compatibility(const Histogram1D & h) const{
     if (get_nbins() != h.get_nbins() || xmin!=h.xmin || xmax != h.xmax){
        fail_check_compatibility(h);
     }
 }
Ejemplo n.º 24
0
void VolumeInformation::computeInformation() {

    if (!volume_.hasData()) {
        numVoxels_.set(0);
        numSignificant_.set(0);
        minValue_.set(0.f);
        maxValue_.set(0.f);
        meanValue_.set(0.f);
        standardDeviation_.set(0.f);
        entropy_.set(0.f);
        return;
    }

    const VolumeRAM* volume = volume_.getData()->getRepresentation<VolumeRAM>();
    tgtAssert(volume, "No input volume");
    size_t numVoxels = volume->getNumVoxels();
    tgt::vec2 intensityRange = volume->elementRange();

    numVoxels_.setMaxValue(static_cast<int>(numVoxels));
    numVoxels_.set(static_cast<int>(numVoxels));

    numSignificant_.setMaxValue(static_cast<int>(numVoxels));
    numSignificant_.set(static_cast<int>(VolumeOperatorNumSignificant::APPLY_OP(volume_.getData())));

    // compute the entropy of the volume
    // E(H) = -\sum_{i=0}^{K-1}{H_p(i) \log_2(H_p(i)}
    // with H_p(i): normalized histrogram with intensity value i
    int histMax = tgt::iround(intensityRange.y);
    // handle float data as if it was 16 bit to prevent overflow
    histMax = tgt::clamp(histMax, 0, 1<<16);//TODO

    Histogram1D histogram = createHistogram1DFromVolume(volume_.getData(), histMax);
    double entropy = 0.0;
    for (size_t i = 0; i < static_cast<size_t>(histMax); ++i) {
        uint64_t value = histogram.getBucket(static_cast<int>(i));

        if (value == 0)
            continue;

        double hi = static_cast<double>(value) / static_cast<double>(numVoxels);
        double loghi = log(hi);

        entropy += hi * loghi;
    }
    entropy *= -1;
    entropy_.setMaxValue(intensityRange.y);
    entropy_.set(static_cast<float>(entropy));

    // min value
    minValue_.setMinValue(intensityRange.x);
    minValue_.setMaxValue(intensityRange.y);
    //minValue_.set(static_cast<float>(histogram.getSignificantRange().x));
    float min = volume_.getData()->getDerivedData<VolumeMinMax>()->getMinNormalized();
    minValue_.set(min);

    //max value
    maxValue_.setMinValue(intensityRange.x);
    maxValue_.setMaxValue(intensityRange.y);
    //maxValue_.set(static_cast<float>(histogram.getSignificantRange().y));
    float max = volume_.getData()->getDerivedData<VolumeMinMax>()->getMaxNormalized();
    maxValue_.set(max);

    // mean value
    double mean = 0.0;
    for (size_t i = 0; i < numVoxels; ++i) {
        float value = volume->getVoxelNormalized(i);
        mean += value;
    }
    mean /= numVoxels;
    meanValue_.setMinValue(intensityRange.x);
    meanValue_.setMaxValue(intensityRange.y);
    meanValue_.set(static_cast<float>(mean));

    // variance
    double variance = 0.0;
    for (size_t i = 0; i < numVoxels; ++i) {
        float value = volume->getVoxelNormalized(i);
        variance += pow(static_cast<double>(value) - mean, 2.0);
    }
    variance /= numVoxels;
    standardDeviation_.setMaxValue(intensityRange.y);
    standardDeviation_.set(static_cast<float>(sqrt(variance)));
}
Ejemplo n.º 25
0
cv::Mat ImageProcessor::invertImage(cv::Mat &origImage) {
	Histogram1D h;
	return h.invert(origImage);
}
int main()
{
	// Read input image
	cv::Mat image= cv::imread("group.jpg",0);
	if (!image.data)
		return 0; 
	// Resize by 70% for book printing
	cv::resize(image, image, cv::Size(), 0.7, 0.7);

	// save grayscale image
	cv::imwrite("groupBW.jpg", image);

    // Display the image
	cv::namedWindow("Image");
	cv::imshow("Image",image);

	// The histogram object
	Histogram1D h;

    // Compute the histogram
	cv::Mat histo= h.getHistogram(image);

	// Loop over each bin
	for (int i=0; i<256; i++) 
		cout << "Value " << i << " = " << histo.at<float>(i) << endl;  

	// Display a histogram as an image
	cv::namedWindow("Histogram");
	cv::imshow("Histogram",h.getHistogramImage(image));

	// creating a binary image by thresholding at the valley
	cv::Mat thresholded; // output binary image
	cv::threshold(image,thresholded,
		          60,    // threshold value
				  255,   // value assigned to pixels over threshold value
				  cv::THRESH_BINARY); // thresholding type
 
	// Display the thresholded image
	cv::namedWindow("Binary Image");
	cv::imshow("Binary Image",thresholded);
	thresholded = 255 - thresholded;
	cv::imwrite("binary.bmp",thresholded);

	// Equalize the image
	cv::Mat eq= h.equalize(image);

	// Show the result
	cv::namedWindow("Equalized Image");
	cv::imshow("Equalized Image",eq);

	// Show the new histogram
	cv::namedWindow("Equalized Histogram");
	cv::imshow("Equalized Histogram",h.getHistogramImage(eq));

	// Stretch the image, setting the 1% of pixels at black and 1% at white
	cv::Mat str= h.stretch(image,0.01f);

	// Show the result
	cv::namedWindow("Stretched Image");
	cv::imshow("Stretched Image",str);

	// Show the new histogram
	cv::namedWindow("Stretched Histogram");
	cv::imshow("Stretched Histogram",h.getHistogramImage(str));

	// Create an image inversion table
	int dim(256);
	cv::Mat lut(1,  // 1 dimension
		&dim,       // 256 entries
		CV_8U);     // uchar
	// or cv::Mat lut(256,1,CV_8U);

	for (int i=0; i<256; i++) {
		
		lut.at<uchar>(i)= 255-i;
	}

	// Apply lookup and display negative image
	cv::namedWindow("Negative image");
	cv::imshow("Negative image",h.applyLookUp(image,lut));

	cv::waitKey();
	return 0;
}
Ejemplo n.º 27
0
cv::Mat ImageProcessor::getHistogram(cv::Mat &origImage) {
	Histogram1D h;
	return h.getHistogramImage(origImage);
}
Ejemplo n.º 28
0
int main()
{
    VideoCapture cap(1);
    cap.set(CV_CAP_PROP_FRAME_WIDTH,640);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT,480);
    if(!cap.isOpened())
        return -1;
    Mat edges, dst, color_dst,gredst;
    CvMemStorage* storage =NULL;
    IplImage* img = NULL;
    for(;;)
    {
        Mat frame;
        cap >> frame;
        edges = frame;
        cvtColor(frame, gredst, CV_BGR2GRAY);
        cvtColor(frame, dst, CV_BGR2GRAY);
        vertx1.clear();
        vertx2.clear();
        vertx3.clear();
        vertx4.clear();
        Mat bgr[3];
        split(edges, bgr);
        Histogram1D h;
        MatND histo = h.getHistogram(bgr[0]);



        colorSegmentation(edges, dst);
        colorSegmentation1(edges,gredst);
        //imshow("rectanger", dst);
        //Houghlinesp
        //GaussianBlur(dst, dst, Size(7,7),1.5,1.5);

        cvtColor( dst, color_dst, CV_GRAY2BGR );

        //Canny( dst, dst, 60, 180, 3 );
        //for(int i = 0; i < 1; i++)GaussianBlur(dst, dst, Size(7,7),3,3);

        //double
        /*vector<Vec4i> lines;


        //cvShowImage("Transform",&img);


        HoughLinesP( dst, lines, 1, CV_PI/180, 60, 30, 0);



        for( size_t i = 0; i < lines.size(); i++ )
        {
            double theta = atan( fabs(lines[i][3] - lines[i][1]) / fabs(lines[i][2] - lines[i][0]));
            if (fabs(theta - CV_PI / 2) < CV_PI/180 * 6 || fabs(theta) < CV_PI/180 * 6)
            {
                line( color_dst, Point(lines[i][0], lines[i][1]),
                      Point(lines[i][2], lines[i][3]), Scalar(0,0,255), 3, 8 );
            }

        }*/



        //Canny(edges, edges,0,90,3);
        imshow("init graph", edges);
        //imshow("rectanger", dst);

        // 转换成opencv1.x处理

        //IplImage img0(dst);
        pyrUp(dst,dst,Size(dst.cols*2,dst.rows*2));
        pyrDown(dst,dst,Size(dst.cols/2,dst.rows/2));
        pyrUp(gredst,gredst,Size((gredst.cols)*2,(gredst.rows)*2));
        pyrDown(gredst,gredst,Size((gredst.cols)/2,(gredst.rows)/2));


        IplImage img0 = IplImage(dst);
        IplImage img1 = IplImage(gredst);
        img = &img0;
        //img = &IplImage(dst);
        //cvShowImage("Transform",img);
        storage = cvCreateMemStorage(0);
        drawSquares( img, findSquares4( img, storage ) );
        img = &img1;
        storage = cvCreateMemStorage(0);
        drawSquares1( img, findSquares4( img, storage ) );



        //imshow("rectanger_line", color_dst);
        //imshow("qq", dst);
        char c= waitKey(33);
        if(c==27)  break;
    }
}
//majorAxis and minorAxis is the estimated particle size in px
void ProgSortByStatistics::processInprocessInputPrepareSPTH(MetaData &SF, bool trained)
{
    //#define DEBUG
    PCAMahalanobisAnalyzer tempPcaAnalyzer0;
    PCAMahalanobisAnalyzer tempPcaAnalyzer1;
    PCAMahalanobisAnalyzer tempPcaAnalyzer2;
    PCAMahalanobisAnalyzer tempPcaAnalyzer3;
    PCAMahalanobisAnalyzer tempPcaAnalyzer4;

    //Morphology
    tempPcaAnalyzer0.clear();
    //Signal to noise ratio
    tempPcaAnalyzer1.clear();
    tempPcaAnalyzer2.clear();
    tempPcaAnalyzer3.clear();
    //Histogram analysis, to detect black points and saturated parts
    tempPcaAnalyzer4.clear();

    double sign = 1;//;-1;
    int numNorm = 3;
    int numDescriptors0=numNorm;
    int numDescriptors2=4;
    int numDescriptors3=11;
    int numDescriptors4 = 10;

    MultidimArray<float> v0(numDescriptors0);
    MultidimArray<float> v2(numDescriptors2);
    MultidimArray<float> v3(numDescriptors3);
    MultidimArray<float> v4(numDescriptors4);

    if (verbose>0)
    {
        std::cout << " Sorting particle set by new xmipp method..." << std::endl;
    }

    int nr_imgs = SF.size();
    if (verbose>0)
        init_progress_bar(nr_imgs);

    int c = XMIPP_MAX(1, nr_imgs / 60);
    int imgno = 0, imgnoPCA=0;

    bool thereIsEnable=SF.containsLabel(MDL_ENABLED);
    bool first=true;

    // We assume that at least there is one particle
    size_t Xdim, Ydim, Zdim, Ndim;
    getImageSize(SF,Xdim,Ydim,Zdim,Ndim);

    //Initialization:
    MultidimArray<double> nI, modI, tempI, tempM, ROI;
    MultidimArray<bool> mask;
    nI.resizeNoCopy(Ydim,Xdim);
    modI.resizeNoCopy(Ydim,Xdim);
    tempI.resizeNoCopy(Ydim,Xdim);
    tempM.resizeNoCopy(Ydim,Xdim);
    mask.resizeNoCopy(Ydim,Xdim);
    mask.initConstant(true);

    MultidimArray<double> autoCorr(2*Ydim,2*Xdim);
    MultidimArray<double> smallAutoCorr;

    Histogram1D hist;
    Matrix2D<double> U,V,temp;
    Matrix1D<double> D;

    MultidimArray<int> radial_count;
    MultidimArray<double> radial_avg;
    Matrix1D<int> center(2);
    MultidimArray<int> distance;
    int dim;
    center.initZeros();

    v0.initZeros(numDescriptors0);
    v2.initZeros(numDescriptors2);
    v3.initZeros(numDescriptors3);
    v4.initZeros(numDescriptors4);

    ROI.resizeNoCopy(Ydim,Xdim);
    ROI.setXmippOrigin();
    FOR_ALL_ELEMENTS_IN_ARRAY2D(ROI)
    {
        double temp = std::sqrt(i*i+j*j);
        if ( temp < (Xdim/2))
            A2D_ELEM(ROI,i,j)= 1;
        else
            A2D_ELEM(ROI,i,j)= 0;
    }

    Image<double> img;
    FourierTransformer transformer(FFTW_BACKWARD);

    FOR_ALL_OBJECTS_IN_METADATA(SF)
    {
        if (thereIsEnable)
        {
            int enabled;
            SF.getValue(MDL_ENABLED,enabled,__iter.objId);
            if ( (enabled==-1)  )
            {
                imgno++;
                continue;
            }
        }

        img.readApplyGeo(SF,__iter.objId);
        if (targetXdim!=-1 && targetXdim!=XSIZE(img()))
        	selfScaleToSize(LINEAR,img(),targetXdim,targetXdim,1);

        MultidimArray<double> &mI=img();
        mI.setXmippOrigin();
        mI.statisticsAdjust(0,1);
        mask.setXmippOrigin();
        //The size of v1 depends on the image size and must be declared here
        int numDescriptors1 = XSIZE(mI)/2; //=100;
        MultidimArray<float> v1(numDescriptors1);
        v1.initZeros(numDescriptors1);

        double var = 1;
        normalize(transformer,mI,tempI,modI,0,var,mask);
        modI.setXmippOrigin();
        tempI.setXmippOrigin();
        nI = sign*tempI*(modI*modI);
        tempM = (modI*modI);

        A1D_ELEM(v0,0) = (tempM*ROI).sum();
        int index = 1;
        var+=2;
        while (index < numNorm)
        {
            normalize(transformer,mI,tempI,modI,0,var,mask);
            modI.setXmippOrigin();
            tempI.setXmippOrigin();
            nI += sign*tempI*(modI*modI);
            tempM += (modI*modI);
            A1D_ELEM(v0,index) = (tempM*ROI).sum();
            index++;
            var+=2;
        }

        nI /= tempM;
        tempPcaAnalyzer0.addVector(v0);
        nI=(nI*ROI);

        auto_correlation_matrix(mI,autoCorr);
        if (first)
        {
            radialAveragePrecomputeDistance(autoCorr, center, distance, dim);
            first=false;
        }
        fastRadialAverage(autoCorr, distance, dim, radial_avg, radial_count);

        for (int n = 0; n < numDescriptors1; ++n)
            A1D_ELEM(v1,n)=(float)DIRECT_A1D_ELEM(radial_avg,n);

        tempPcaAnalyzer1.addVector(v1);

#ifdef DEBUG

        //String name = "000005@Images/Extracted/run_002/extra/BPV_1386.stk";
        String name = "000010@Images/Extracted/run_001/extra/KLH_Dataset_I_Training_0028.stk";
        //String name = "001160@Images/Extracted/run_001/DefaultFamily5";

        std::cout << img.name() << std::endl;

        if (img.name()==name2)
        {
            FileName fpName    = "test_1.txt";
            mI.write(fpName);
            fpName    = "test_2.txt";
            nI.write(fpName);
            fpName    = "test_3.txt";
            tempM.write(fpName);
            fpName    = "test_4.txt";
            ROI.write(fpName);
            //exit(1);
        }
#endif
        nI.binarize(0);
        int im = labelImage2D(nI,nI,8);
        compute_hist(nI, hist, 0, im, im+1);
        size_t l;
        int k,i,j;
        hist.maxIndex(l,k,i,j);
        A1D_ELEM(hist,j)=0;
        hist.maxIndex(l,k,i,j);
        nI.binarizeRange(j-1,j+1);

        double x0=0,y0=0,majorAxis=0,minorAxis=0,ellipAng=0;
        size_t area=0;
        fitEllipse(nI,x0,y0,majorAxis,minorAxis,ellipAng,area);

        A1D_ELEM(v2,0)=majorAxis/((img().xdim) );
        A1D_ELEM(v2,1)=minorAxis/((img().xdim) );
        A1D_ELEM(v2,2)= (fabs((img().xdim)/2-x0)+fabs((img().ydim)/2-y0))/((img().xdim)/2);
        A1D_ELEM(v2,3)=area/( (double)((img().xdim)/2)*((img().ydim)/2) );

        for (int n=0 ; n < numDescriptors2 ; n++)
        {
            if ( std::isnan(std::abs(A1D_ELEM(v2,n))))
                A1D_ELEM(v2,n)=0;
        }

        tempPcaAnalyzer2.addVector(v2);

        //mI.setXmippOrigin();
        //auto_correlation_matrix(mI*ROI,autoCorr);
        //auto_correlation_matrix(nI,autoCorr);
        autoCorr.window(smallAutoCorr,-5,-5, 5, 5);
        smallAutoCorr.copy(temp);
        svdcmp(temp,U,D,V);

        for (int n = 0; n < numDescriptors3; ++n)
            A1D_ELEM(v3,n)=(float)VEC_ELEM(D,n); //A1D_ELEM(v3,n)=(float)VEC_ELEM(D,n)/VEC_ELEM(D,0);

        tempPcaAnalyzer3.addVector(v3);


        double minVal=0.;
        double maxVal=0.;
        mI.computeDoubleMinMax(minVal,maxVal);
        compute_hist(mI, hist, minVal, maxVal, 100);

        for (int n=0 ; n <= numDescriptors4-1 ; n++)
        {
            A1D_ELEM(v4,n)= (hist.percentil((n+1)*10));
        }
        tempPcaAnalyzer4.addVector(v4);

#ifdef DEBUG

        if (img.name()==name1)
        {
            FileName fpName    = "test.txt";
            mI.write(fpName);
            fpName    = "test3.txt";
            nI.write(fpName);
        }
#endif
        imgno++;
        imgnoPCA++;

        if (imgno % c == 0 && verbose>0)
            progress_bar(imgno);
    }

    tempPcaAnalyzer0.evaluateZScore(2,20,trained);
    tempPcaAnalyzer1.evaluateZScore(2,20,trained);
    tempPcaAnalyzer2.evaluateZScore(2,20,trained);
    tempPcaAnalyzer3.evaluateZScore(2,20,trained);
    tempPcaAnalyzer4.evaluateZScore(2,20,trained);

    pcaAnalyzer.push_back(tempPcaAnalyzer0);
    pcaAnalyzer.push_back(tempPcaAnalyzer1);
    pcaAnalyzer.push_back(tempPcaAnalyzer1);
    pcaAnalyzer.push_back(tempPcaAnalyzer3);
    pcaAnalyzer.push_back(tempPcaAnalyzer4);

}