Esempio n. 1
0
    QImage img2qimg(cv::Mat& img)
    {

         // convert the color to RGB (OpenCV uses BGR)
         switch (img.type()) {
         case CV_8UC1:
            cv::cvtColor(img, img, CV_GRAY2RGB);
            break;
         case CV_8UC3:
            cv::cvtColor(img, img, CV_BGR2RGB);
            break;
         }


         // return the QImage
         return QImage((uchar*) img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
    }
Esempio n. 2
0
float pixkit::qualityassessment::SNS(const cv::Mat &src1b,int ksize){

	//////////////////////////////////////////////////////////////////////////
	///// exception
	if(src1b.type()!=CV_8UC1){
		CV_Assert(false);
	}
	//////////////////////////////////////////////////////////////////////////
	///// process
	Mat src1b_bar;
	cv::medianBlur(src1b,src1b_bar,ksize);
	Mat	m_diff;
	cv::absdiff(src1b,src1b_bar,m_diff);
	//////////////////////////////////////////////////////////////////////////
	///// get sns
	return cv::sum(m_diff)[0]	/	((double)src1b.rows*src1b.cols*255.)	*	100.;
}
Esempio n. 3
0
//改变图像对比度和亮度值的主方法  
void OpenCV_Function::contrastAndBrightByTrackbar(){
	system("color5F");   
	g_srcImage=cv::imread("girl-t1.jpg");

	g_resultImage= cv::Mat::zeros( g_srcImage.size(), g_srcImage.type());

	cv::namedWindow( WINDOW_NAME1, cv::WINDOW_AUTOSIZE );
	cv::namedWindow( WINDOW_NAME2, cv::WINDOW_AUTOSIZE );

	cv::createTrackbar("对比度:", WINDOW_NAME2,&g_nContrastValue,300,contrastAndBright );  
    cv::createTrackbar("亮   度:",WINDOW_NAME2,&g_nBrightValue,200,contrastAndBright );  

	contrastAndBright(g_nContrastValue,0);  
    contrastAndBright(g_nBrightValue,0);  


}
Esempio n. 4
0
//===========================================================================
void Tracker::InitShape(cv::Rect &r,cv::Mat &shape)
{
  assert((shape.rows == _rshape.rows) && (shape.cols == _rshape.cols) &&
	 (shape.type() == CV_64F));
  int i,n = _rshape.rows/2; double a,b,tx,ty;
  a = r.width*cos(_simil[1])*_simil[0] + 1;
  b = r.width*sin(_simil[1])*_simil[0];
  tx = r.x + r.width/2  + r.width *_simil[2];
  ty = r.y + r.height/2 + r.height*_simil[3];
  cv::MatIterator_<double> sx = _rshape.begin<double>();
  cv::MatIterator_<double> sy = _rshape.begin<double>()+n;
  cv::MatIterator_<double> dx =   shape.begin<double>();
  cv::MatIterator_<double> dy =   shape.begin<double>()+n;
  for(i = 0; i < n; i++,++sx,++sy,++dx,++dy){
    *dx = a*(*sx) - b*(*sy) + tx; *dy = b*(*sx) + a*(*sy) + ty;
  }return;
}
Esempio n. 5
0
inline QImage MainWindow::cvMatToQImage( const cv::Mat &inMat )
{
    switch ( inMat.type() )
    {
    // 8-bit, 4 channel
    case CV_8UC4:
    {
        QImage image( inMat.data, inMat.cols, inMat.rows, inMat.step, QImage::Format_RGB32 );

        return image;
    }

    // 8-bit, 3 channel
    case CV_8UC3:
    {
        QImage image( inMat.data, inMat.cols, inMat.rows, inMat.step, QImage::Format_RGB888 );

        return image.rgbSwapped();
    }

    // 8-bit, 1 channel
    case CV_8UC1:
    {
        static QVector<QRgb>  sColorTable;

        // only create our color table once
        if ( sColorTable.isEmpty() )
        {
            for ( int i = 0; i < 256; ++i )
                sColorTable.push_back( qRgb( i, i, i ) );
        }

        QImage image( inMat.data, inMat.cols, inMat.rows, inMat.step, QImage::Format_Indexed8 );

        image.setColorTable( sColorTable );

        return image;
    }

    default:
        //qWarning() << "ASM::cvMatToQImage() - cv::Mat image type not handled in switch:" << inMat.type();
        break;
    }

    return QImage();
}
Esempio n. 6
0
    template <typename T, template <typename> class Interpolator> void remapImpl(const cv::Mat& src, const cv::Mat& xmap, const cv::Mat& ymap, cv::Mat& dst, int borderType, cv::Scalar borderVal)
    {
        const int cn = src.channels();

        cv::Size dsize = xmap.size();

        dst.create(dsize, src.type());

        for (int y = 0; y < dsize.height; ++y)
        {
            for (int x = 0; x < dsize.width; ++x)
            {
                for (int c = 0; c < cn; ++c)
                    dst.at<T>(y, x * cn + c) = Interpolator<T>::getValue(src, ymap.at<float>(y, x), xmap.at<float>(y, x), c, borderType, borderVal);
            }
        }
    }
Esempio n. 7
0
static inline void show(const char* name, const cv::Mat& img)
{
  if(img.type() == CV_32F)
  {
    double min, max;

    cv::minMaxLoc(img, &min, &max);

    cv::Mat display = img / max;

    cv::imshow(name, display);
  }
  else
  {
    cv::imshow(name, img);
  }
}
void Video2Log::logImage(cv::Mat &matImgOrig)
{
  cv::Mat matImg;
  naoth::Image repImg;


  ASSERT(matImgOrig.type() == CV_8SC3);

  // always resize to 320x240
  ASSERT(repImg.width() == 320);
  ASSERT(repImg.height() == 240);

  if(matImgOrig.rows != repImg.height() || matImgOrig.cols != repImg.width())
  {
    cv::resize(matImgOrig, matImg, cv::Size(repImg.width(),repImg.height()));
  }
  else
  {
    matImg = matImgOrig;
  }
  ASSERT(matImg.rows == repImg.height());
  ASSERT(matImg.cols == repImg.width());

  // we need YCbCr color space
  cv::cvtColor(matImg, matImg, CV_RGB2YCrCb);

  // convert the classical way
  for(unsigned int x=0; x < matImg.cols && x < repImg.width(); x++)
  {
    for(unsigned int y=0; y < matImg.rows && y < repImg.height(); y++)
    {
      cv::Vec3b v = matImg.at<cv::Vec3b>(y,x);
      Pixel p;
      p.y = v[0];
      p.u = v[1];
      p.v = v[2];
      repImg.set(x, y, p);
    }
  }

  // write out
  std::stringstream& stream = mgr.log(frameNumber, "Image");
  naoth::Serializer<naoth::Image>::serialize(repImg, stream);

  frameNumber++;
}
Esempio n. 9
0
void energy2RGB(const cv::Mat &energyImage, cv::Mat &outputImage) {
	std::vector<cv::Mat> channels;

	cv::Mat o = cv::Mat::ones(cv::Size(energyImage.cols, energyImage.rows),
			energyImage.type()) * 255;

	cv::Mat energyNormalized;
	normalize(energyImage, energyNormalized, 0, 255, cv::NORM_MINMAX);
	channels.push_back(energyNormalized);
	channels.push_back(o);
	channels.push_back(o);

	cv::Mat resultHSV;
	cv::merge(channels, resultHSV);

	cv::cvtColor(resultHSV, outputImage, CV_HSV2BGR);
}
void cannyEdgeDetect()
{
    cv::VideoCapture cap(0);                                    //capture the video from web cam

    if ( !cap.isOpened() )                                      // if not success, exit program
    {
         std::cout << "Cannot open the web cam" << std::endl;
         return;
    }

    // Load input image

    while(true)
    {

        bool bSuccess = cap.read(src);                    // read a new frame from video

         if (!bSuccess)                                         //if not success, break loop
        {
             std::cout << "Cannot read a frame from video stream" << std::endl;
             break;
         }

     /// Create a matrix of the same type and size as src (for dst)
     dst.create( src.size(), src.type() );

     /// Convert the image to grayscale
     cv::cvtColor( src, src_gray, CV_BGR2GRAY );

     /// Create a window
     cv::namedWindow( window_name, CV_WINDOW_AUTOSIZE );

     /// Create a Trackbar for user to enter threshold
     cv::createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );

     /// Show the image
     CannyThreshold(0, 0);

     if (cv::waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
     {
         std::cout << "esc key is pressed by user" << std::endl;
         break;
     }
 }

}
Esempio n. 11
0
	/** 
	 * @brief	
	 * @details	
	 *
	 * @param[in]	orig
	 *				.
	 * @param[out]	out
	 *				.
	 * @param[in]	out_width
	 *				.
	 * @param[in]	out_height
	 *				.
	 * @param[out]	roi_out
	 *				.
	 *
	 * @return	
	 *			
	 */
	double fitt_image(cv::Mat& orig, cv::Mat& out, int out_width, int out_height, cv::Rect* roi_out){
		//Test Input
		if(orig.cols <= 0 || orig.rows <= 0) return -1;

		//Create Output
		out = cv::Mat::zeros(cv::Size(out_width,out_height),orig.type());

		//Calc ROI and Resize Image
		if(!roi_out) roi_out = new cv::Rect();
		cv::Mat temp;
		int w,h;
		double output_ratio = (double)out.cols / (double)out.rows;
		double input_ratio = (double)orig.cols / (double)orig.rows;

		double ratio = 1.0;

		if(input_ratio < output_ratio){
			ratio = (float)out.rows/(float)orig.rows;
			w = orig.cols *ratio;
			h = orig.rows *ratio;

			cv::resize(orig,temp,cv::Size(w,h),0.0,0.0,cv::INTER_CUBIC);
		
			roi_out->x = (out.cols - w) / 2.0;
			roi_out->y = 0;
			roi_out->width = w;
			roi_out->height = h;
		}
		else{
			ratio = (float)out.cols/(float)orig.cols;
			w = orig.cols *ratio;
			h = orig.rows *ratio;

			cv::resize(orig,temp,cv::Size(w,h),0.0,0.0,cv::INTER_CUBIC);
		
			roi_out->x = 0;
			roi_out->y = (out.rows - h) / 2.0;
			roi_out->width = w;
			roi_out->height = h;
		}

		//Copy to Destination
		temp.copyTo(out(*roi_out));

		return ratio;
	}
Esempio n. 12
0
inline image_format opencv_get_mat_image_format(const cv::Mat &mat)
{
    switch(mat.type()){
        case CV_8UC4:
            return image_format(CL_BGRA, CL_UNORM_INT8);
        case CV_16UC4:
            return image_format(CL_BGRA, CL_UNORM_INT16);
        case CV_32F:
            return image_format(CL_INTENSITY, CL_FLOAT);
        case CV_32FC4:
            return image_format(CL_RGBA, CL_FLOAT);
        case CV_8UC1:
            return image_format(CL_INTENSITY, CL_UNORM_INT8);
    }

    BOOST_THROW_EXCEPTION(opencl_error(CL_IMAGE_FORMAT_NOT_SUPPORTED));
}
Esempio n. 13
0
//vector_Mat
void Mat_to_vector_Mat(cv::Mat& mat, std::vector<cv::Mat>& v_mat)
{
    v_mat.clear();
    if(mat.type() == CV_32SC2 && mat.cols == 1)
    {
        v_mat.reserve(mat.rows);
        for(int i=0; i<mat.rows; i++)
        {
            Vec<int, 2> a = mat.at< Vec<int, 2> >(i, 0);
            long long addr = (((long long)a[0])<<32) | (a[1]&0xffffffff);
            Mat& m = *( (Mat*) addr );
            v_mat.push_back(m);
        }
    } else {
        LOGD("Mat_to_vector_Mat() FAILED: mat.type() == CV_32SC2 && mat.cols == 1");
    }
}
Esempio n. 14
0
void ImageUtil::saveMatBinary(cv::Mat &mat, std::string filename) {
	int header[3] = { mat.rows, mat.cols, mat.type() };
	FILE *out = my_io_openFileWrite1(filename.c_str());
	int64_t n = fwrite(header, sizeof(int), 3, out);
	my_assert_equalInt("written bytes", n, 3);
	size_t size_pixel = 0;
	if (mat.type() == CV_8S || mat.type() == CV_8U)
		size_pixel = 1;
	else if (mat.type() == CV_16S || mat.type() == CV_16U)
		size_pixel = 2;
	else if (mat.type() == CV_32S || mat.type() == CV_32F)
		size_pixel = 4;
	else if (mat.type() == CV_64F)
		size_pixel = 8;
	int length = mat.rows * mat.cols;
	int64_t n2 = fwrite(mat.data, size_pixel, length, out);
	my_assert_equalInt("written bytes", n2, length);
	fclose(out);
}
Esempio n. 15
0
template<typename T>void ComputationWorker::divideReal(cv::Mat& input, cv::Mat& factor, cv::Mat& out) {
    assert(input.type() == CV_32FC2 || input.type() == CV_64FC2);
    assert(out.type() == CV_32FC2 || out.type() == CV_64FC2);
    assert(factor.type() == CV_32FC1 || factor.type() == CV_64FC1);

    out.forEach<Point_<T>>([&input, &factor](Point_<T> &p, const int pos[]) -> void {
        T fac = factor.at<T>(pos[0], pos[1]);
        Point_<T> inp = input.at<Point_<T>>(pos[0], pos[1]);
        p.x = inp.x / fac;
        p.y = inp.y / fac;
    });    
}
cv::Mat sg::padKernelFFT( cv::Mat const & input, cv::Size const & paddedSize )
{
  cv::Mat result = cv::Mat::zeros( paddedSize, input.type() );

  // Get the 4 quadrants of the input kernel
  int hwx = input.cols / 2;
  int hwy = input.rows / 2;
  int px = hwx;
  int py = hwy;

  int fftW = paddedSize.width;
  int fftH = paddedSize.height;

  if( input.cols %2 != 0 )
    ++px;

  if( input.rows % 2 != 0 )
    ++py;

  cv::Mat  q0( input, cv::Rect( 0, 0, px, py ) );
  cv::Mat q02( result, cv::Rect( fftW - px, fftH - py, px, py ) );

  cv::Mat  q1( input, cv::Rect( px, 0, hwx, py ) );
  cv::Mat q12( result, cv::Rect( 0, fftH - py, hwx, py ) );

  cv::Mat  q2( input, cv::Rect( 0, py, px, hwy ) );
  cv::Mat q22( result, cv::Rect( fftW - px, 0, px, hwy ) );

  cv::Mat  q3( input, cv::Rect( px, py, hwx, hwy ) );
  cv::Mat q32( result, cv::Rect( 0, 0, hwx, hwy ) );

  q0.copyTo( q02 );
  q1.copyTo( q12 );
  q2.copyTo( q22 );
  q3.copyTo( q32 );

  // if our filter doesn't have real and complex components, make the complex part zeros
  if( result.channels() < 2 )
  {
    cv::Mat planes[] = { result, cv::Mat::zeros( result.size(), CV_32F ) };
    cv::merge( planes, 2, result );
  }

  return result;
}
cv::Mat dehaze(cv::Mat& image,cv::Mat& difference,cv::Point ale,int k,int rho,double xi)
{
     cv::Mat output = cv::Mat(image.rows,image.cols,image.type());
     float c = 1.0/k;
     vector<float> ci(k);
     std::generate(ci.begin(),ci.end(),Generator(c));

     vector<cv::Mat> layers;
     vector<cv::Mat> mask_layers;
     vector<cv::Mat> diff_layers;
     Vec3f ale_temp= image.at<cv::Vec3f>(ale);

     for(int i=0;i<ci.size();i++)
     {
         cv::Mat layer=image.clone();

         layer-=(ci[i]*ale_temp);
         cv::Mat inverse = inverseImage(layer);
         cv::Mat diff = haze_difference(layer,inverse);
         cv::Mat mask = inverseImageMask(inverse,diff,rho,xi);
         //ale = airlight_estimation(layer,mask);
         //ale_temp= image.at<float>(ale);

         #ifdef DEBUG
             cv::Mat inv,m,l;
             cv::normalize(layer, l, 0, 255, NORM_MINMAX, CV_32FC3);
             cv::normalize(inverse, inv, 0, 255, NORM_MINMAX, CV_32FC3);
             cv::normalize(mask, m, 0, 255, NORM_MINMAX, CV_32FC3);
             imwrite("layer_"+to_string(i)+".jpg",l);
             imwrite("layer_inv_"+to_string(i)+".jpg",inv);
             imwrite("layer_mask_"+to_string(i)+".jpg",m);
         #endif
         layers.push_back(layer);
         mask_layers.push_back(mask);
         diff_layers.push_back(diff);
     }
     for(int count=layers.size()-1;count>-1;count--)
     {
        cv::Mat temp=mask_layers[count];
        //addWeighted(layers[count],1.0,mask_layers[count],1.0,0.0,temp);
        float weight=(float)count/10.0;
        addWeighted(output,weight,temp,1.0-weight,0.0,output);
     }
     return output;
}
cv::Mat PeopleDetector::preprocessImage(cv::Mat& input_image)
{
	// todo:
	return input_image;

	// do a modified census transform
	cv::Mat output(input_image.cols, input_image.rows, input_image.type());
	//cv::Mat smoothedImage = input_image.clone();
	//cv::GaussianBlur(smoothedImage, smoothedImage, cv::Size(3,3), 0, 0, cv::BORDER_REPLICATE);

	for (int v = 0; v < input_image.rows; v++)
	{
		uchar* srcPtr = input_image.ptr(v);
		//uchar* smoothPtr = smoothedImage.ptr(v);
		uchar* outPtr = output.ptr(v);
		for (int u = 0; u < input_image.cols; u++)
		{
			int ctOutcome = 0;
			int offset = -1;
			for (int dv = -1; dv <= 1; dv++)
			{
				for (int du = -1; du <= 1; du++)
				{
					if (dv == 0 && du == 0)
						continue;
					offset++;
					if (v + dv < 0 || v + dv >= input_image.rows || u + du < 0 || u + du >= input_image.cols)
						continue;
					//if (*smoothPtr < *(srcPtr+dv*input_image.step+du)) ctOutcome += 1<<offset;
					if (*srcPtr < *(srcPtr + dv * input_image.step + du))
						ctOutcome += 1 << offset;
				}
			}
			*outPtr = ctOutcome;

			srcPtr++;
			outPtr++;
		}
	}

	//	cv::imshow("census transform", output);
	//	cv::waitKey();

	return output;
}
static void myDrawEpipolarLinesDouble(const std::string& title, const cv::Matx<T1, 3, 3> F, const cv::Mat& img1, const cv::Mat& img2,
    const std::vector<cv::Point_<T2> > points1, const std::vector<cv::Point_<T2> > points2) {
  cv::Mat outImg(img1.rows, img1.cols * 2, CV_8UC3);
  cv::Mat outImgInit(img1.rows, img1.cols * 2, CV_8UC3);
  cv::Rect rect1(0, 0, img1.cols, img1.rows);
  cv::Rect rect2(img1.cols, 0, img1.cols, img1.rows);
  /*
   * Allow color drawing
   */
  if (img1.type() == CV_8U) {
    cv::cvtColor(img1, outImg(rect1), CV_GRAY2BGR);
    cv::cvtColor(img2, outImg(rect2), CV_GRAY2BGR);
  } else {
    img1.copyTo(outImg(rect1));
    img2.copyTo(outImg(rect2));
  }
  outImg.copyTo(outImgInit);
  std::vector<cv::Vec<T2, 3> > epilines1, epilines2;
  cv::computeCorrespondEpilines(points1, 1, F, epilines1); //Index starts with 1
  cv::computeCorrespondEpilines(points2, 2, F, epilines2);

  CV_Assert(points1.size() == points2.size() && points2.size() == epilines1.size() && epilines1.size() == epilines2.size());

  cv::RNG rng(0);
  for (size_t i = 0; i < points1.size(); i++) {

    outImg.copyTo(outImgInit);
    cv::Scalar color(rng(256), rng(256), rng(256));
    cv::Mat temp = outImgInit.clone();
    cv::Mat tmp2 = outImgInit(rect2);
    cv::Mat tmp1 = outImgInit(rect1);
    //outImg.copyTo(temp);

    cv::line(tmp2, cv::Point(0, -epilines1[i][2] / epilines1[i][1]),
        cv::Point(img1.cols, -(epilines1[i][2] + epilines1[i][0] * img1.cols) / epilines1[i][1]), cv::Scalar(0, 255, 0));
    cv::circle(tmp2, points1[i], 3, cv::Scalar(255, 0, 0), -1, CV_AA);

    cv::line(tmp1, cv::Point(0, -epilines2[i][2] / epilines2[i][1]),
        cv::Point(img2.cols, -(epilines2[i][2] + epilines2[i][0] * img2.cols) / epilines2[i][1]), cv::Scalar(0, 255, 0));
    cv::circle(tmp1, points2[i], 3, cv::Scalar(255, 0, 0), -1, CV_AA);

    cv::imshow(title, outImgInit);
    cv::waitKey(0);
  }
}
Esempio n. 20
0
cv::Mat RFeatures::createImageType( ImageType imgType, cv::Mat img) throw (ImageTypeException)
{
    cv::Mat m;
    cv::Mat_<cv::Vec3f> tmp;    // for cielab
    cv::Mat_<byte> bem; // Binary edge map for EDT
    switch ( imgType)
    {
        case BGR:
            if ( img.type() != CV_8UC3)
                throw ImageTypeException( "[EXCEPTION] RFeatures::createImageType: Given image is not already CV_8UC3!");
            m = img.clone();
            break;
        case Grey:
            if ( img.type() != CV_8UC3 && img.type() != CV_8UC1)
                throw ImageTypeException( "[EXCEPTION] RFeatures::createImageType: Cannot make ImageType::Grey from non CV_8UC3 image!");
            m = RFeatures::flatten( img);
            break;
        case Light:
            if ( img.type() != CV_8UC3)
                throw ImageTypeException( "[EXCEPTION] RFeatures::createImageType: Cannot make ImageType::Light from non CV_8UC3 image!");
            m = RFeatures::getLightness( img, 1.0);
            break;
        case CIELab:
            if ( img.type() != CV_8UC3)
                throw ImageTypeException( "[EXCEPTION] RFeatures::createImageType: Cannot make ImageType::CIELab from non CV_8UC3 image!");
            img.convertTo( tmp, CV_32F, 1.0/255);
            cv::cvtColor( tmp, m, CV_BGR2Lab);
            break;
        case Depth:
            if ( img.type() != CV_32FC1)
                throw ImageTypeException( "[EXCEPTION] RFeatures::createImageType: Cannot make ImageType::Depth from non CV_32FC1 image!");
            m = RFeatures::truncateAndScale( img, MAX_RANGE_M, 1);
            break;
        case EDT:
            if ( img.type() != CV_32FC1)
                throw ImageTypeException( "[EXCEPTION] RFeatures::createImageType: Cannot make ImageType::EDT from non CV_32FC1 image!");
            m = RFeatures::truncateAndScale( img, MAX_RANGE_M, 1);
            bem = RFeatures::EDTFeatureExtractor::createBinaryEdgeMap( m, 15, 10);
            //RFeatures::showImage( RFeatures::convertForDisplay( bem), "EDT: Binary Edge Map", true); // DEBUG
            m =  RFeatures::EDTFeature( bem)();
            break;
        default:
            throw ImageTypeException( "[EXCEPTION] RFeatures::createImageType: Invalid ImageType (ENUM DEFINITION ERROR!)");
    }   // end switch

    return m;
}   // end createImageType
Esempio n. 21
0
/**
 * Fast version of setImage: assumes BGR mat (CV_8UC3), does not resize widget
 * @param mat matrix to use for current image
 */
void image_widget::set_bgr_image_fast(const cv::Mat& mat) {

	// Convert the image to the RGB888 format
	// assume BGR image
#ifdef DO_IMG_TYPE_CHECKING
	if(mat.type() != CV_8UC3){
		err(std::invalid_argument) << "Error caught in image_widget::set_image_fast...Wrong image type: " << mat.type() << "." << std::endl << enderr;
	}
#endif

	cvtColor(mat, tmp, CV_BGR2RGB);

	// Assign OpenCV's image buffer to the QImage. Note that the bytesPerLine parameter
	// is 3*width because each pixel has three bytes.
	image = QImage(tmp.data, tmp.cols, tmp.rows, tmp.cols * 3, QImage::Format_RGB888);

	repaint();
}
Esempio n. 22
0
void FunctionUtils::printDescriptors(const cv::Mat& descriptors) {
	for (int i = 0; i < descriptors.rows; i++) {
		printf("[");
		for (int j = 0; j < descriptors.cols; j++) {
			if (descriptors.type() == CV_8U) {
				std::bitset<8> byte(descriptors.at<uchar>(i, j));
				printf("%s,", byte.to_string().c_str());
			} else {
				printf("%f,", (float) descriptors.at<float>(i, j));
			}
		}
//		int decimal = BinToDec(descriptors.row(i));
//		if (descriptors.type() == CV_8U) {
//			printf(" = %ld (%d)", decimal, NumberOfSetBits(decimal));
//		}
		printf("]\n");
	}
}
Esempio n. 23
0
/*!
\param[out] ofs output file stream
\param[in] out_mat mat to save
*/
bool writeMatBinary(std::ofstream& ofs, const cv::Mat& out_mat)
{
	if(!ofs.is_open()){
		return false;
	}
	if(out_mat.empty()){
		int s = 0;
		ofs.write((const char*)(&s), sizeof(int));
		return true;
	}
	int type = out_mat.type();
	ofs.write((const char*)(&out_mat.rows), sizeof(int));
	ofs.write((const char*)(&out_mat.cols), sizeof(int));
	ofs.write((const char*)(&type), sizeof(int));
	ofs.write((const char*)(out_mat.data), out_mat.elemSize() * out_mat.total());

	return true;
}
    int max_angle_hist(cv::Mat hist)
    {
        CV_Assert(hist.cols == 1);
        CV_Assert(hist.type() == CV_32S);

        int angle = 0;
        int max = -1;
        for(int r=0; r < hist.rows; r++)
        {
            int v = hist.at<int>(r, 0);
            if(v > max)
            {
                max = v;
                angle = r;
            }
        }
        return angle;
    }
Esempio n. 25
0
// ".png" or ".jpg"
std::vector<unsigned char> compressImage(const cv::Mat & image, const std::string & format)
{
	std::vector<unsigned char> bytes;
	if(!image.empty())
	{
		if(image.type() == CV_32FC1)
		{
			//save in 8bits-4channel
			cv::Mat bgra(image.size(), CV_8UC4, image.data);
			cv::imencode(format, bgra, bytes);
		}
		else
		{
			cv::imencode(format, image, bytes);
		}
	}
	return bytes;
}
Esempio n. 26
0
void addNoise(cv::Mat &image)
{
    if (image.channels() > 1)
    {
        SD_TRACE("addNoise : image should have single channel");
        return;
    }
    int initDepth=image.depth();
    if (initDepth < CV_32F)
        image.convertTo(image, CV_32F);

    cv::Mat noise(image.rows, image.cols, image.type());
    cv::randn(noise, 100, 25);
    image = image + noise;

    if (initDepth == CV_8U)
        ImageCommon::convertTo8U(image, image);
}
void FlowIOOpenCVWrapper::write(std::string path, const cv::Mat & flow) {
    assert(flow.channels() == 2);
    assert(flow.type() == CV_32FC2);
    
    int rows = flow.rows;
    int cols = flow.cols;
    
    CFloatImage cFlow(cols, rows, 2);
    
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cFlow.Pixel(j, i, 0) = flow.at<cv::Vec2f>(i, j)[0];
            cFlow.Pixel(j, i, 1) = flow.at<cv::Vec2f>(i, j)[1];
        }
    }
    
    WriteFlowFile(cFlow, path.c_str());
}
Esempio n. 28
0
 //! 字符预处理
 cv::Mat preprocessChar(cv::Mat in){
     //Remap image
     int h = in.rows;
     int w = in.cols;
     int charSize = CHAR_SIZE;	//统一每个字符的大小
     cv::Mat transformMat = cv::Mat::eye(2, 3, CV_32F);
     int m = MAX(w, h);
     transformMat.at<float>(0, 2) = m / 2 - w / 2;
     transformMat.at<float>(1, 2) = m / 2 - h / 2;
     
     cv::Mat warpImage(m, m, in.type());
     warpAffine(in, warpImage, transformMat, warpImage.size(), cv::INTER_LINEAR, cv::BORDER_CONSTANT, cvScalar(0));
     
     cv::Mat out;
     resize(warpImage, out, cvSize(charSize, charSize));
     
     return out;
 }
Esempio n. 29
0
cv::Mat ImgCutter::cut_center_only(const cv::Mat &src, cv::Rect center_rect){
    cv::Mat mask = cv::Mat::zeros(src.size(), src.type());
    std::vector<cv::Point> contour;
    contour.push_back(cv::Point(center_rect.x, center_rect.y));
    contour.push_back(cv::Point(center_rect.x+center_rect.width, center_rect.y));
    contour.push_back(cv::Point(center_rect.x+center_rect.width, center_rect.y+center_rect.height));
    contour.push_back(cv::Point(center_rect.x, center_rect.y+center_rect.height));
    std::vector<std::vector<cv::Point> > contours;
    contours.push_back(contour);
    if(mask.channels()>1){
        cv::drawContours(mask, contours, -1, cv::Scalar(255,255,255), CV_FILLED);
    }else{
        cv::drawContours(mask, contours, -1, 255, CV_FILLED);
    }
    cv::Mat dst;
    cv::bitwise_and(src, mask, dst);
    return dst;
}
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;
}