// How to do sharpening without explicitly using a convolution filter and cv::filter2D
void RFeatures::sharpen_OLD( const cv::Mat &img, cv::Mat &out)
{
    out.create( img.size(), img.type());    // Allocate if necessary

    int channels = img.channels();
    int nc = img.cols * channels;

    for ( int j = 1; j < img.rows-1; ++j) // All rows except first and last
    {
        const uchar* previous = img.ptr<const uchar>(j-1); // Previous row
        const uchar* current = img.ptr<const uchar>(j); // Current row
        const uchar* next = img.ptr<const uchar>(j+1);  // Next row
        uchar* output = out.ptr<uchar>(j);  // Output row

        for ( int i = channels; i < nc - channels; ++i)   // All columns except first and last
        {
            uchar v = 5*current[i] - current[i-channels] - current[i+channels] - previous[i] - next[i];
            *output++ = cv::saturate_cast<uchar>(v);
        }   // end for
    }   // end for

    // Set the unprocesses pixels to 0
    cv::Scalar s(0);
    if (img.channels() == 3)
        s = cv::Scalar(0,0,0);
    out.row(0).setTo( s);
    out.row(out.rows-1).setTo( s);
    out.col(0).setTo( s);
    out.col(out.cols-1).setTo( s);
}   // end sharpen_OLD
void sharpen2(const cv::Mat& image, cv::Mat& result)
{

    result.create(image.size(), image.type()); // allocate if necessary

    int step = image.step1();
    const uchar* previous = image.data;        // ptr to previous row
    const uchar* current = image.data + step;  // ptr to current row
    const uchar* next = image.data + 2 * step; // ptr to next row
    uchar* output = result.data + step;        // ptr to output row

    for (int j = 1; j < image.rows - 1; j++)
    { // for each row (except first and last)
        for (int i = 1; i < image.cols - 1; i++)
        { // for each column (except first and last)

            output[i] = cv::saturate_cast<uchar>(5 * current[i] - current[i - 1] - current[i + 1] -
                                                 previous[i] - next[i]);
        }

        previous += step;
        current += step;
        next += step;
        output += step;
    }

    // Set the unprocess pixels to 0
    result.row(0).setTo(cv::Scalar(0));
    result.row(result.rows - 1).setTo(cv::Scalar(0));
    result.col(0).setTo(cv::Scalar(0));
    result.col(result.cols - 1).setTo(cv::Scalar(0));
}
Exemple #3
0
void optimizeEmat (cv::Mat p1, cv::Mat p2, cv::Mat K, cv::Mat *E)
	// input: p1, p2, normalized image points correspondences
{
	int n = p1.cols;
	double* measurement = new double[n];	
	for (int i=0; i<n; ++i) 
		measurement[i] = 0;	
	double opts[LM_OPTS_SZ], info[LM_INFO_SZ];
	opts[0]=LM_INIT_MU*0.5; //
	opts[1]=1E-50;
	opts[2]=1E-100; // original 1e-50
	opts[3]=1E-20;
	opts[4]= -LM_DIFF_DELTA;
	int matIter = 100;
	
	cv::Mat R1, R2, t;
	
	decEssential (E, &R1, &R2, &t);
	
	cv::Mat Rt = // find true R and t
		findTrueRt(R1,R2,t,mat2cvpt(p1.col(0)),mat2cvpt(p2.col(0)));
	
	if(Rt.cols < 3) return;

	cv::Mat R =  Rt.colRange(0,3);
	t = Rt.col(3);
	Matrix3d Rx;
	Rx << R.at<double>(0,0), R.at<double>(0,1), R.at<double>(0,2),
		R.at<double>(1,0), R.at<double>(1,1), R.at<double>(1,2),
		R.at<double>(2,0), R.at<double>(2,1), R.at<double>(2,2);
	Quaterniond q(Rx);

	double para[7] = {q.w(), q.x(), q.y(), q.z(), t.at<double>(0),
		t.at<double>(1), t.at<double>(2)};

	data_optimizeEmat data;
	data.p1 = p1;
	data.p2 = p2;
	data.K  = K;
	
	int ret = dlevmar_dif(costfun_optimizeEmat, para, measurement, 7, n,
		matIter, opts, info, NULL, NULL, (void*)&data);
	delete[] measurement;
	q.w() = para[0];
	q.x() = para[1];
	q.y() = para[2];
	q.z() = para[3];
	q.normalize();
	
	for (int i=0; i<3; ++i)
		for (int j=0; j<3; ++j)
			R.at<double>(i,j) = q.matrix()(i,j);

	cv::Mat tx = (cv::Mat_<double>(3,3)<< 0, -para[6], para[5],
		para[6], 0 ,  -para[4],
		-para[5], para[4], 0 );
	tx = tx/sqrt(para[4]*para[4]+para[5]*para[5]+para[6]*para[6]);
	*E = tx * R;
//	cout<<" "<<R<<endl<<para[4]<<"\t"<<para[5]<<"\t"<<para[6]<<endl;
}
void sharpen(const cv::Mat& image, cv::Mat& result){
    // allocate if necessary
    result.create(global::image.size(), global::image.type());
    std::cout << "Size: " << global::image.size() << std::endl;
    std::cout << "Cols: " << global::image.cols << "\n" << "Rows: " << global::image.rows << std::endl;

    for (int j=1; j<global::image.rows-1; j++){ // for all rows except first and last
        const uchar* previous = global::image.ptr<const uchar>(j-1); // previous row
        const uchar* current = global::image.ptr<const uchar>(j); // current row
        const uchar* next = global::image.ptr<const uchar>(j+1); // next row

        uchar* output = result.ptr<uchar>(j); // output row

        for (int i=1; i<global::image.cols-1; i++){
            *output = cv::saturate_cast<uchar>(5*current[i]-current[i-1]-current[i+1]-previous[i]-next[i]);
            output++;

        }
    }

    // set unprocessed pixels to 0
    result.row(0).setTo(cv::Scalar(0));
    result.row(result.rows-1).setTo(cv::Scalar(0));
    result.col(0).setTo(cv::Scalar(0));
    result.col(result.cols-1).setTo(cv::Scalar(0));
}
void Processor::sharpen(const cv::Mat &image, cv::Mat &result) {

	startTimer();
// allocate if necessary
	result.create(image.rows, image.cols, image.type());
	for (int j = 1; j < image.rows - 1; j++) { // for all rows
// (except first and last)
		const uchar* previous = image.ptr<const uchar>(j - 1); // previous row
		const uchar* current = image.ptr<const uchar>(j); // current row
		const uchar* next = image.ptr<const uchar>(j + 1); // next row
		uchar* output = result.ptr<uchar>(j); // output row
		for (int i = 1; i < image.cols - 1; i++) {
			for (int k = 0; k < image.channels(); k++) {
				result.at<cv::Vec3b>(j, i)[k] = cv::saturate_cast<uchar>(
						5 * image.at<cv::Vec3b>(j, i)[k]
								- image.at<cv::Vec3b>(j, i - 1)[k]
								- image.at<cv::Vec3b>(j, i + 1)[k]
								- image.at<cv::Vec3b>(j - 1, i)[k]
								- image.at<cv::Vec3b>(j + 1, i)[k]);
			}
		}
	}
// Set the unprocess pixels to 0
	result.row(0).setTo(cv::Scalar(0));
	result.row(result.rows - 1).setTo(cv::Scalar(0));
	result.col(0).setTo(cv::Scalar(0));
	result.col(result.cols - 1).setTo(cv::Scalar(0));

	stopTimer("Sharpen");
}
Exemple #6
0
void sharpen(const cv::Mat& image, cv::Mat& result)
{
    //allocate if necessary
    result.create(image.size(),image.type());

    for(int j= 1; j < image.rows-1; ++j) { // for all rows
                                // except the first and last row
        const uchar* previous =
                image.ptr<uchar>(j-1);
        const uchar* current =
                image.ptr<uchar>(j);
        const uchar* next =
                image.ptr<uchar>(j+1);

        uchar* output = result.ptr<uchar>(j); // output row

        for(int i= 1; i < (image.cols-1) * image.channels(); ++i) {
            // stature_cast: avoid the mathematical expression applied on the pixels leads to a
            // result that goes out of the range of the permited pixel value( 0 - 255)
            *output ++ = cv::saturate_cast<uchar>(5 * current[i] - current[i-1] - current[i+1] -
                         previous[i] - next[i]);
        }
    }


        //set the unprocess pixels to zero
        result.row(0).setTo(cv::Scalar(0));
        result.row(result.rows-1).setTo(cv::Scalar(0));
        result.col(0).setTo(cv::Scalar(0));
        result.col(result.cols-1).setTo(cv::Scalar(0));

}
// M - step
// Improves the mean, covariance, and weight of each gaussian using
// the responsibilites computed in the E step
void GMM::_M(const cv::Mat &gamma, const cv::Mat &samples)
{
    for(int k = 0; k < _Gaussians.size(); k++)
    {
        // Get the kth gaussian responsibilities
        cv::Mat gammak = gamma.col(k);
        
        // Compute Nk, the sum of all responsibilties for this gaussian
        double Nk = cv::sum(gammak)[0];
        
        // Update the mean
        cv::Mat uNew = cv::Mat::zeros(gammak.cols, 1, CV_64F);
        for(int n = 0; n < gammak.rows; n++)
        {
            uNew += gammak.at<double>(n, 1) * samples.col(n);
        }
        
        uNew /= Nk;
        _Gaussians[k].Mean() = uNew;
        
        // Update the covariance
        cv::Mat sigmaNew = cv::Mat::zeros(gammak.rows, gammak.rows, CV_64F);
        for(int n = 0; n < gammak.rows; n++)
        {
            cv::Mat meanDistance = samples.col(n) - uNew;
            sigmaNew += gammak.at<double>(n, 1) * (meanDistance * meanDistance.t());
        }
        
        sigmaNew /= Nk;
        _Gaussians[k].Covariance() = sigmaNew;
        
        // Udpate weight
        _Gaussians[k].Weight() = Nk / samples.cols;
    }
}
Exemple #8
0
  void sharpen(cv::Mat &image, cv::Mat &out)
  {
      out.create(image.size(), image.type());
      for(int j=1; j < image.rows-1;j++)
      {
	  const uchar* previous = image.ptr<const uchar>(j-1);
	  const uchar* current  = image.ptr<const uchar>(j);
	  const uchar* next     = image.ptr<const uchar>(j+1);
	  uchar* output = out.ptr<uchar>(j);
	  
	  for(int i=1; i<image.cols-1; i++)
	  {
	      *output++=cv::saturate_cast<uchar>(
			  5*current[i]-current[i-1]
			  -current[i+1]-previous[1]-next[1]);
		  
	      
	  }
      }
      out.row(0).setTo(cv::Scalar(0));
      out.row(out.rows-1).setTo(cv::Scalar(0));
      out.col(0).setTo(cv::Scalar(0));
      out.col(out.cols-1).setTo(cv::Scalar(0));
      
      
    
    
    
  }
Exemple #9
0
vector<pair<int, double>> OMP(cv::Mat x, cv::Mat base, int coeff_count)
{
	vector<pair<int, double>> result;
	cv::Mat residual = x.clone();
	for (int i = 0; i < coeff_count; ++i)
	{
		int max_index = 0;
		double max_value = 0;
		for (int j = 0; j < base.cols; ++j)
		{
			double current_value = abs(
				static_cast<cv::Mat>(residual.t() * base.col(j)).at<double>(0));
			if (current_value > max_value)
			{
				max_value = current_value;
				max_index = j;
			}
		}

		result.push_back(make_pair(max_index, 0));
		cv::Mat sparse_base(base.rows, result.size(), CV_64FC1);
		for (int j = 0; j < result.size(); ++j)
			base.col(result[j].first).copyTo(sparse_base.col(j));

		cv::Mat beta;
		cv::solve(sparse_base.t() * sparse_base, 
			sparse_base.t() * x, beta, cv::DECOMP_SVD);
		for (int j = 0; j < result.size(); ++j)
			result[j].second = beta.at<double>(j);
		residual -= sparse_base * beta;
	}

	return result;
}
/* This function will rearrange dataset for training in a random order. This step is
* necessary to make training more accurate.
*/
void LetterClassifier::ShuffleDataset(cv::Mat &training_data, cv::Mat &label_mat, int numIter)
{
	/* initialize random seed: */
	srand(time(NULL));
	int x = 0, y = 0;

	assert(training_data.cols == label_mat.rows);

	int numData = training_data.cols;
	if (numIter <= 0)
		numIter = numData;

	if (training_data.type() != CV_32FC1)
		training_data.convertTo(training_data, CV_32FC1);
	cv::Mat temp_data_mat(training_data.rows, 1, CV_32FC1);
	cv::Mat temp_label_mat(1, 1, CV_32FC1);


	// Interate 'numIter' to rearrange dataset
	for (int n = 0; n < numIter; n++)
	{
		x = (rand() % numData);
		y = (rand() % numData);

		// swap data
		training_data.col(x).copyTo(temp_data_mat.col(0));
		training_data.col(y).copyTo(training_data.col(x));
		temp_data_mat.col(0).copyTo(training_data.col(y));

		// swap label
		label_mat.row(x).copyTo(temp_label_mat.row(0));
		label_mat.row(y).copyTo(label_mat.row(x));
		temp_label_mat.row(0).copyTo(label_mat.row(y));
	}
}
Exemple #11
0
// Update stage
void ParticleFilter::update(cv::Mat measurement)
{
	// Propose indicators
	std::vector<int> indicators = resample(gmm.weight, gmm.nParticles);
	std::vector<double> weights;
	wsum = 0;
	int i;
	std::vector<state_params> temp;
	
	for (int j = 0; j < gmm.nParticles; j++) //update KF for each track using indicator samples
	{
		i = indicators[j];
		gmm.KFtracker[i].predict(gmm.tracks[j].state,gmm.tracks[j].cov);
		weights.push_back(mvnpdf(measurement.col(j),gmm.KFtracker[i].H*gmm.tracks[j].state+gmm.KFtracker[i].BH,gmm.KFtracker[i].H*gmm.tracks[j].cov*gmm.KFtracker[i].H.t()+gmm.KFtracker[i].R));
		wsum = wsum + weights[j];
		gmm.KFtracker[i].update(measurement.col(j),gmm.tracks[j].state,gmm.tracks[j].cov);
		temp.push_back(gmm.tracks[j]);
	}
	
		
	for (int i = 0; i < (int)gmm.tracks.size(); i++)
	{
		weights[i] = weights[i]/wsum;
	}
	
	// Re-sample tracks
	indicators.clear();
	indicators = resample(weights, gmm.nParticles);
	for (int j = 0; j < gmm.nParticles; j++) //update KF for each track using indicator samples
	{
		gmm.tracks[j] = temp[indicators[j]];
	}
	wsum = 1.0;
}
void sharpen(const cv::Mat& image, cv::Mat& result)
{

    result.create(image.size(), image.type()); // allocate if necessary

    for (int j = 1; j < image.rows - 1; j++)
    { // for all rows (except first and last)

        const uchar* previous = image.ptr<const uchar>(j - 1); // previous row
        const uchar* current = image.ptr<const uchar>(j);      // current row
        const uchar* next = image.ptr<const uchar>(j + 1);     // next row

        uchar* output = result.ptr<uchar>(j); // output row

        for (int i = 1; i < image.cols - 1; i++)
        {

            *output++ = cv::saturate_cast<uchar>(5 * current[i] - current[i - 1] - current[i + 1] -
                                                 previous[i] - next[i]);
            //			output[i]=
            //cv::saturate_cast<uchar>(5*current[i]-current[i-1]-current[i+1]-previous[i]-next[i]);
        }
    }

    // Set the unprocess pixels to 0
    result.row(0).setTo(cv::Scalar(0));
    result.row(result.rows - 1).setTo(cv::Scalar(0));
    result.col(0).setTo(cv::Scalar(0));
    result.col(result.cols - 1).setTo(cv::Scalar(0));
}
Exemple #13
0
void AlphaBlender::performBlendX(const cv::Mat& image1,const cv::Mat& image2,cv::Mat& outputImage){
	double alpha=1,beta=0;
	for(int i=0;i<image1.cols;i++){

		beta=(double)i/(image1.cols-1);
		alpha=1-beta;
		cv::addWeighted(image1.col(i),alpha,image2.col(i),beta,0,outputImage.col(i));
	}
}
inline
cv::Mat
opt_feat::Shift_Image( cv::Mat src_in, int num_pixels_x, int num_pixels_y)
{


    cv::Mat img_out;


    cv::Mat rot_mat = (cv::Mat_<double>(2,3) << 1, 0, num_pixels_x, 0, 1, num_pixels_y);
    warpAffine( src_in, img_out, rot_mat, src_in.size() );

    if (num_pixels_x>0) //Move right
    {

        cv::Mat col = src_in.col(0);
        cv::Mat row = src_in.row(0);


        for (int i=0; i<abs(num_pixels_x); ++i)
        {
            col.col(0).copyTo(img_out.col(i));

        }

        for (int i=0; i<abs(num_pixels_y); ++i)
        {
            row.row(0).copyTo(img_out.row(i));
            //src_in.copyTo(img_out,crop);
        }
    }

    if (num_pixels_x<0) //Move left
    {

        int w = src_in.size().width;
        int h = src_in.size().height;
        cv::Mat col = src_in.col(w-1);
        cv::Mat row = src_in.row(h-1);

        for (int i=w-abs(num_pixels_x) ; i<w; ++i)
        {
            col.col(0).copyTo(img_out.col(i));
            //row.row(0).copyTo(img_out.row(i));
        }

        for (int i=h-abs(num_pixels_y) ; i<h; ++i)
        {
            //col.col(0).copyTo(img_out.col(i));
            row.row(0).copyTo(img_out.row(i));
        }
    }


    return img_out;
}
Exemple #15
0
void drawBgImage(cv::Mat & render, cv::Mat & bgImage, float yaw, float fov, int nBeams) {

	int bgImageStart = bgImage.cols - yaw*nBeams/fov;
	for(int c = 0; c<render.cols; c++) {
		int cBgImage = bgImageStart + c;
		if(cBgImage >= bgImage.cols) cBgImage -= bgImage.cols;
		bgImage.col(cBgImage).copyTo(render.col(c));
	}

}
Exemple #16
0
bool fund_ransac (cv::Mat pts1, cv::Mat pts2, cv::Mat F, vector<uchar>& mask, double distThresh, double confidence)
	// running 8-point algorithm 
	// re-estimation at the end
	// Input: points pairs normalized by camera matrix K
	// output: 
{
	int maxIterNum = 500, N = pts1.cols;
	int iter = 0;
	vector<int> rnd;
	for (int i=0; i<N; ++i)		rnd.push_back(i);
	cv::Mat mss1(2,8,CV_32F), mss2(2,8,CV_32F);
	vector<int> maxInlierSet;
	cv::Mat bestF;
	vector<uchar> maxInlierMask(N);

	while (iter < maxIterNum) {
		++iter;
		// --- choose minimal solution set: mss1<->mss2
//		random_shuffle(rnd.begin(),rnd.end());
//		random_unique(rnd.begin(), rnd.end(), mss1.cols);
		for (int i=0; i < mss1.cols; ++i) {
			pts1.col((i*iter)%N).copyTo(mss1.col(i));
			pts2.col((i*iter)%N).copyTo(mss2.col(i));
		}		
		// compute minimal solution by 8-point
		cv::Mat minF = cv::findFundamentalMat(mss1.t(),mss2.t(), cv::FM_8POINT);
		// find concensus set
		vector<int> curInlierSet;
		vector<uchar> inlierMask(N);
			for (int i=0; i<N; ++i) {
				float dist_sq = fund_samperr_float(pts1.col(i), pts2.col(i), minF);
				if (dist_sq < distThresh*distThresh) {
					curInlierSet.push_back(i);
					inlierMask[i] = 1; 
				} else {
					inlierMask[i] = 0;
				}
			}
			if(curInlierSet.size() > maxInlierSet.size()) {
				maxInlierSet = curInlierSet;
				bestF = minF;
				maxInlierMask = inlierMask;
			}

		//re-compute maximum iteration number:maxIterNum
		maxIterNum = abs(log(1-confidence)/log(1-pow(double(maxInlierSet.size())/N,8.0)));
	}
	if (maxInlierSet.size() < mss1.cols) {
		return false;
	}
	mask = maxInlierMask;
	F = bestF;
	return true;
}
Exemple #17
0
cv::Mat normComplex(const cv::Mat& A, cv::Mat& out)
{//try to implement divComplex
  try
  {
    if (A.channels() != 2)
    {
        throw CustomException("normComplex: Must be two-channel image.");
    }
    //a+bi/c+di=(ac+bd/c^2+d^2)+(bc-ad/c^2+d^2)i
    //Divide every matrix element by the complex value at the origin (frequency 0,0)
    auto sA = splitComplex(A);
    cv::Mat norm = cv::repeat(A.col(0).row(0), A.rows, A.cols);
    
    
    auto sF = splitComplex(norm);
    //Zero value the imaginary part of the normalizations factor, it should be zero anyway
    sF.second = cv::Mat::zeros(sF.first.size(), sF.first.type());
    
    cv::Mat den = (sF.first).mul(sF.first) + (sF.second).mul(sF.second);
    out = makeComplex( ( (sA.first).mul(sF.first)  + (sA.second).mul(sF.second) )/den,
                     ( (sA.second).mul(sF.first) - (sA.first).mul(sF.second)  )/den  );
    //In order to keep generic image type, it's a matrix instead of a complex value
    return makeComplex(sF.first, sF.second);
  }
  catch(...)
  {
    throw;
  }
}
    cv::Mat get_histogram(cv::Mat image, int hist_type, int type)
    {
        CV_Assert(image.type() == CV_8U);
        cv::Mat hist;

        if(hist_type == HIST_ROW)
        {
            hist = cv::Mat::zeros(image.rows, 1, CV_32S);
            for(int t=0; t < image.rows; t++)
            {
                cv::Scalar sum = cv::sum(image.row(t));
                hist.at<uint>(t, 0) = sum[0];
            }
        }
        else if(hist_type == HIST_COL)
        {
            hist = cv::Mat::zeros(image.cols, 1, CV_32S);
            for(int c=0; c < image.cols; c++)
            {
                cv::Scalar sum = cv::sum(image.col(c));
                hist.at<uint>(c, 0) = sum[0];
            }
        }

        if(type != CV_32S)
            hist.convertTo(hist, type);

        return hist;
    }
Exemple #19
0
void centration(cv::Mat &X){
	cv::Mat center = calc_center(X);
	//std::cout << center << std::endl;
	for(int i=0; i<X.cols; i++){
		X.col(i) -= center;
	}
}
Exemple #20
0
 // !获取垂直和水平方向直方图
 cv::Mat ProjectedHistogram(cv::Mat src, int t){
     /*
     cv::Mat image1;
     IplImage* image2;
     image2 = cvCreateImage(cvSize(image1.cols,image1.rows),8,3);
     IplImage ipltemp=image1;
     cvCopy(&ipltemp,image2);
      
      cv::Mat src = cv::cvarrToMat(img);
     //*/
     
     int sz = (t) ? src.rows : src.cols;
     cv::Mat mhist = cv::Mat::zeros(1, sz, CV_32F);
     
     for (int j = 0; j<sz; j++){
         cv::Mat data = (t) ? src.row(j) : src.col(j);
         
         mhist.at<float>(j) =countNonZero(data);	//统计这一行或一列中,非零元素的个数,并保存到mhist中
     }
     
     //Normalize histogram
     double min, max;
     minMaxLoc(mhist, &min, &max);
     
     if (max>0)
         mhist.convertTo(mhist, -1, 1.0f / max, 0);//用mhist直方图中的最大值,归一化直方图
     //IplImage *dst;
     //IplImage tmp = mhist;
     //cvCopy(&tmp, dst);
     return mhist;
 }
Exemple #21
0
cv::Mat sum(cv::Mat mat, int dim)
{
	if (dim==1)
	{
		cv::Mat r(1, mat.rows, CV_64F, cv::Scalar(0.0));

		for (int i = 0; i < mat.rows; i++)
		{
			r.at<double>(1,i) = cv::sum(mat.row(i))[0];
		}
		return r;
	}
	else if (dim==2)
	{
		cv::Mat r(mat.cols, 1, CV_64F, cv::Scalar(0.0));

		for (int i = 0; i < mat.rows; i++)
		{
			r.at<double>(i,1) = cv::sum(mat.col(i))[0];
		}
		return r;
	}
	else
		throw "dim is not 1 or 2.";
}
// E - step
// Computes the responsibility of each gaussian for each data sample
// returns an nxk matrix (the gamma matrix) where n is the number of features and k is the number of gaussians
cv::Mat GMM::_E(const cv::Mat &samples) const
{
    const GMM &model = *this;
    cv::Mat gamma(samples.cols, _Gaussians.size(), CV_64F);
    
    for(int n = 0; n < samples.cols; n++) // For each sample
    {
        double gmmXn = model(samples.col(n)); // GMM in its current state evaluated for this sample
        
        for(int k = 0; k < _Gaussians.size(); k++) // and each gaussian
        {
            gamma.at<double>(n, k) = _Gaussians[k](samples.col(n)) / gmmXn; // Find its responsibility
        }
    }
    
    return gamma;
}
Exemple #23
0
void sharpen(const cv::Mat& image,cv::Mat& result){
	for(int j=1;j<image.rows-1;j++){
		const uchar* previous=image.ptr<const uchar>(j-1);
		const uchar* current=image.ptr<const uchar>(j);
		const uchar* next=image.ptr<const uchar>(j+1);
		      uchar* current4target=result.ptr<uchar>(j);
		for(int i=1;i<image.cols-1;i++){
			*current4target=cv::saturate_cast<uchar>( 5*current[i]-previous[i]-next[i]-current[j-1]-current[j+1] );
			current4target++;
		}
	}
	//first and last row and column
	result.row(0).setTo( cv::Scalar(0) );
	result.row( result.rows-1 ).setTo( cv::Scalar(0) );
	result.col(0).setTo( cv::Scalar(0) );
	result.col( result.cols-1 ).setTo( cv::Scalar(0) );
}
void LetterClassifier::LoadImages(std::vector< std::vector< std::string > > &file_names, cv::Mat &dataset, cv::Mat &labels, cv::Mat &test_dataset, cv::Mat &test_labels)
{
	int num_train_data = 0, num_test_data = 0;
	std::vector< int > num_data;
	for ( size_t i = 0; i < file_names.size(); i++ )
	{
		int num_data_per_class = (int)(file_names[i].size()/(params.train_test_ratio + 1))*params.train_test_ratio;
		num_data_per_class = (num_data_per_class >  params.max_samples_class) ? params.max_samples_class : num_data_per_class;
		num_data.push_back(num_data_per_class);
		num_test_data += ((int)file_names[i].size() - num_data_per_class);
		num_train_data += num_data_per_class;
	}
	std::cout << "Number of TEST data:  " << num_test_data << std::endl;
	std::cout << "Number of TRAIN data: " << num_train_data << std::endl;
	int k = 0, l = 0;
	dataset = cv::Mat(cv::Size(num_train_data, params.letter_size.area()), CV_32F);
	labels = cv::Mat(cv::Size(1, num_train_data), CV_32F);

	test_dataset = cv::Mat(cv::Size(num_test_data, params.letter_size.area()), CV_32F);
	test_labels = cv::Mat(cv::Size(1, num_test_data), CV_32F);
	for ( size_t i = 0; i < file_names.size(); i++ )
	{
		cv::Mat img;
		for ( int j = 0; j < (int)file_names[i].size(); j++ )
		{
			img = cv::imread(file_names[i][j], CV_LOAD_IMAGE_GRAYSCALE);
			cv::resize(img, img, params.letter_size);
			img.convertTo(img, CV_32F);
			img = img.reshape(1, params.letter_size.area());
			if (j < num_data[i])
			{
				img.copyTo(dataset.col(k));
				labels.at<float>(k) = (float)i;
				k++;
			}
			else
			{
				img.copyTo(test_dataset.col(l));
				test_labels.at<float>(l) = (float)i;
				l++;
			}
		}
	}
	labels.convertTo(labels, CV_32S);
	test_labels.convertTo(test_labels, CV_32S);
}
Exemple #25
0
void Transformations::decomposeRt(const cv::Mat &T, cv::Mat &R, cv::Mat &t)
{
  R = T( cv::Range(0,3), cv::Range(0,3) );
  
  if(t.rows == 3 && t.cols == 1)
    t = T( cv::Range(0,3), cv::Range(3,4) );
  else
    t = T.col(4);
}
Exemple #26
0
    cv::Mat getCol(float offset) {
        int col = offset * image.cols;
        if(col < 0)
            col = 0;
        if(col >= image.cols)
            col = image.cols - 1;

        return image.col(col);
    }
Exemple #27
0
/**
 * deConcat	-	de-concat the concatnate image into frames
 *
 * @param src       -   source concatnate image
 * @param framesize	-	frame size
 * @param frames	-	destinate frames
 */
void VideoProcessor::deConcat(const cv::Mat &src,
                              const cv::Size &frameSize,
                              std::vector<cv::Mat> &frames)
{
    for (int i = 0; i < length-1; ++i) {    // get a line if any
        cv::Mat line = src.col(i).clone();
        cv::Mat reshaped = line.reshape(3, frameSize.height).clone();
        frames.push_back(reshaped);
    }
}
cv::Mat circshiftcols(cv::Mat x, int n)
{
	cv::Mat y(x.rows, x.cols, x.type());

	for (int i = 0; i < x.cols; i++)
	{
		int yi = (i+n) % x.cols;
		 x.col(i).copyTo(y.col(yi));
	}
	return y.clone();
}
// same function but using iterator
// this one works only for gray-level image
void sharpenIterator(const cv::Mat &image, cv::Mat &result) {

	cv::Mat_<uchar>::const_iterator it= image.begin<uchar>()+image.cols;
	cv::Mat_<uchar>::const_iterator itend= image.end<uchar>()-image.cols;
	cv::Mat_<uchar>::const_iterator itup= image.begin<uchar>();
	cv::Mat_<uchar>::const_iterator itdown= image.begin<uchar>()+2*image.cols;

	result.create(image.size(), image.type()); // allocate if necessary
	cv::Mat_<uchar>::iterator itout= result.begin<uchar>()+result.cols;

	for ( ; it!= itend; ++it, ++itout, ++itup, ++itdown) {

			*itout= cv::saturate_cast<uchar>(*it *5 - *(it-1)- *(it+1)- *itup - *itdown); 
	}

	// Set the unprocess pixels to 0
	result.row(0).setTo(cv::Scalar(0));
	result.row(result.rows-1).setTo(cv::Scalar(0));
	result.col(0).setTo(cv::Scalar(0));
	result.col(result.cols-1).setTo(cv::Scalar(0));
}
// Computes the likelihood that the GMM that is currently trained
// is the one that generated our data
double GMM::_LogLikelihood(const cv::Mat &samples) const
{    
    const GMM &gmm = *this;
    
    double ll = 0;
    for(int n = 0; n < samples.cols; n++)
    {
        ll += std::log(gmm(samples.col(n)));
    }
    
    return ll;
}