Beispiel #1
0
static
int connectedComponents_sub1(const cv::Mat &I, cv::Mat &L, int connectivity, StatsOp &sop){
    CV_Assert(L.channels() == 1 && I.channels() == 1);
    CV_Assert(connectivity == 8 || connectivity == 4);

    int lDepth = L.depth();
    int iDepth = I.depth();
    using connectedcomponents::LabelingImpl;
    //warn if L's depth is not sufficient?

    CV_Assert(iDepth == CV_8U || iDepth == CV_8S);

    if(lDepth == CV_8U){
        return (int) LabelingImpl<uchar, uchar, StatsOp>()(I, L, connectivity, sop);
    }else if(lDepth == CV_16U){
        return (int) LabelingImpl<ushort, uchar, StatsOp>()(I, L, connectivity, sop);
    }else if(lDepth == CV_32S){
        //note that signed types don't really make sense here and not being able to use unsigned matters for scientific projects
        //OpenCV: how should we proceed?  .at<T> typechecks in debug mode
        return (int) LabelingImpl<int, uchar, StatsOp>()(I, L, connectivity, sop);
    }

    CV_Error(CV_StsUnsupportedFormat, "unsupported label/image type");
    return -1;
}
Beispiel #2
0
bool p3p::solve(cv::Mat& R, cv::Mat& tvec, const cv::Mat& opoints, const cv::Mat& ipoints)
{
    CV_INSTRUMENT_REGION();

    double rotation_matrix[3][3] = {}, translation[3] = {};
    std::vector<double> points;
    if (opoints.depth() == ipoints.depth())
    {
        if (opoints.depth() == CV_32F)
            extract_points<cv::Point3f,cv::Point2f>(opoints, ipoints, points);
        else
            extract_points<cv::Point3d,cv::Point2d>(opoints, ipoints, points);
    }
    else if (opoints.depth() == CV_32F)
        extract_points<cv::Point3f,cv::Point2d>(opoints, ipoints, points);
    else
        extract_points<cv::Point3d,cv::Point2f>(opoints, ipoints, points);

    bool result = solve(rotation_matrix, translation,
                        points[0], points[1], points[2], points[3], points[4],
                        points[5], points[6], points[7], points[8], points[9],
                        points[10], points[11], points[12], points[13], points[14],
                        points[15], points[16], points[17], points[18], points[19]);
    cv::Mat(3, 1, CV_64F, translation).copyTo(tvec);
    cv::Mat(3, 3, CV_64F, rotation_matrix).copyTo(R);
    return result;
}
QImage ImageProcessing::Mat2QImage(const cv::Mat & cvmat)
{
  int height = cvmat.rows;
  int width = cvmat.cols;

  if (cvmat.depth() == CV_8U && cvmat.channels() == 3) {
      QImage img((const uchar*)cvmat.data, width, height, cvmat.step.p[0], QImage::Format_RGB888);
      return img.rgbSwapped();
  }
  else if (cvmat.depth() == CV_8U && cvmat.channels() == 1) {
    if (!s_greyTableInit) {
        for (int i = 0; i < 256; i++){
            s_greyTable.push_back(qRgb(i, i, i));
        }
    }
    QImage img((const uchar*)cvmat.data, width, height, cvmat.step.p[0], QImage::Format_Indexed8);
    img.setColorTable(s_greyTable);
    return img;
  }
  else if (cvmat.depth() == CV_8U && cvmat.channels() == 4) {
    QImage img((const uchar*)cvmat.data, width, height, cvmat.step.p[0], QImage::Format_RGB32);
    return img.rgbSwapped();
}
  else {
      qWarning() << "Image cannot be converted.";
      return QImage();
  }

}
cv::Mat generateGaussianMask(const cv::Mat& covariance,double ingnore_rate){
	assert(covariance.depth()==CV_32F || covariance.depth()==CV_64F);
	cv::Mat mask;
	cvMatTypeTemplateCall(covariance.type(),_generateGaussianMask,mask,float,covariance,ingnore_rate);

	return mask;
}
Beispiel #5
0
void JfrImage_convertColorModePrivate(const JfrImage_ImageHeader* jfrSrc, const cv::Mat& src,
				      JfrImage_ImageHeader* jfrDst, cv::Mat& dst)
{
  JFR_PRECOND(src.depth() == dst.depth(),
	      "convertColorMode: invalid depth");
  JFR_PRECOND(src.cols == dst.cols && src.rows == dst.rows,
              "convertColorMode: invalid size");

  cv::cvtColor(src, dst, JfrImage_convertColorMode(jfrSrc->colorSpace, jfrDst->colorSpace));
}
int StereoMatch::getDisparityImage(cv::Mat& disparity, cv::Mat& disparityImage, bool isColor)
{
	cv::Mat disp8u;
	if (disparity.depth() != CV_8U)
	{
		if (disparity.depth() == CV_8S)
		{
			disparity.convertTo(disp8u, CV_8U);
		} 
		else
		{
			disparity.convertTo(disp8u, CV_8U, 255/(m_numberOfDisparies*16.));
		}
	} 
	else
	{
		disp8u = disparity;
	}

	if (isColor)
	{
		if (disparityImage.empty() || disparityImage.type() != CV_8UC3 || disparityImage.size() != disparity.size())
		{
			disparityImage = cv::Mat::zeros(disparity.rows, disparity.cols, CV_8UC3);
		}

		for (int y=0;y<disparity.rows;y++)
		{
			for (int x=0;x<disparity.cols;x++)
			{
				uchar val = disp8u.at<uchar>(y,x);
				uchar r,g,b;

				if (val==0) 
					r = g = b = 0;
				else
				{
					r = 255-val;
					g = val < 128 ? val*2 : (uchar)((255 - val)*2);
					b = val;
				}

				disparityImage.at<cv::Vec3b>(y,x) = cv::Vec3b(r,g,b);
			}
		}
	} 
	else
	{
		disp8u.copyTo(disparityImage);
	}

	return 1;
}
void getDXsCV(const cv::Mat src1, cv::Mat dest_dx, cv::Mat dest_dy){		
	static double x[5] = {0.0833, -0.6667, 0, 0.6667, -0.0833};					
	static double y[5] = {0.0833, -0.6667, 0, 0.6667, -0.0833};
 
	//x derivative
	cv::Mat weickertX(1, 5, CV_64FC1, x ); // 64FC1 for double
	cv::filter2D(src1, dest_dx, dest_dx.depth(), weickertX, cv::Point(-1, -1), 0, cv::BORDER_CONSTANT);
	
	//y derivative
	cv::Mat weickertY(5, 1, CV_64FC1, y ); // 64FC1 for double
	cv::filter2D(src1, dest_dy, dest_dy.depth(), weickertY, cv::Point(-1, -1), 0, cv::BORDER_CONSTANT);
}
Beispiel #8
0
QImage OpencvWidget::cvMat2QImage(cv::Mat &cvImg)
{
    if (!cvImg.empty())
    {
		cv::cvtColor(cvImg, cvImg, CV_BGR2RGB);
        if (cvImg.channels()==1 && cvImg.depth()== CV_8U)
            return QImage((uchar *)cvImg.data,cvImg.cols,cvImg.rows,cvImg.step,QImage::Format_Indexed8);
        else 
			if (cvImg.channels()==3 && cvImg.depth()== CV_8U)
				return QImage((uchar *)cvImg.data,cvImg.cols,cvImg.rows,cvImg.step,QImage::Format_RGB888);
    }
    return  QImage();
}
GuidedFilterMono::GuidedFilterMono(const cv::Mat &origI, int r, double eps) : r(r), eps(eps)
{
    if (origI.depth() == CV_32F || origI.depth() == CV_64F)
        I = origI.clone();
    else
        I = convertTo(origI, CV_32F);

    Idepth = I.depth();

    mean_I = boxfilter(I, r);
    cv::Mat mean_II = boxfilter(I.mul(I), r);
    var_I = mean_II - mean_I.mul(mean_I);
}
Beispiel #10
0
void drwnLBPFilterBank::filter(const cv::Mat& img, std::vector<cv::Mat>& response) const
{
    // check input
    DRWN_ASSERT(img.data != NULL);
    if (response.empty()) {
        response.resize(this->numFilters());
    }
    DRWN_ASSERT(response.size() == this->numFilters());

    if (img.channels() != 1) {
        cv::Mat tmp(img.rows, img.cols, img.depth());
        cv::cvtColor(img, tmp, CV_RGB2GRAY);
        return filter(tmp, response);
    }
    DRWN_ASSERT_MSG(img.depth() == CV_8U, "image must be 8-bit");

    // allocate output channels as 32-bit floating point
    for (unsigned i = 0; i < response.size(); i++) {
        if ((response[i].rows == img.rows) && (response[i].cols == img.cols) &&
            (response[i].depth() == CV_32F) && (response[i].channels() == 1)) {
            response[i].setTo(0.0f);
        } else {
            response[i] = cv::Mat::zeros(img.rows, img.cols, CV_32FC1);
        }
    }

    for (int y = 0; y < img.rows; y++) {

        const unsigned char *p = img.ptr<const unsigned char>(y);
        const unsigned char *p_prev = (y == 0) ? p : img.ptr<const unsigned char>(y - 1);
        const unsigned char *p_next = (y == img.rows - 1) ? p : img.ptr<const unsigned char>(y + 1);

        // 4-connected neighbourhood
        for (int x = 0; x < img.cols; x++) {
            if (p[x] > p_prev[x]) response[0].at<float>(y, x) = 1.0f;
            if ((x < img.cols - 1) && (p[x] > p[x + 1])) response[1].at<float>(y, x) = 1.0f;
            if (p[x] > p_next[x]) response[2].at<float>(y, x) = 1.0f;
            if ((x > 0) && (p[x] > p[x - 1])) response[3].at<float>(y, x) = 1.0f;
        }

        // 8-connected neighbourhood
        if (_b8Neighbourhood) {
            for (int x = 0; x < img.cols; x++) {
                if ((p[x] > p_prev[x]) && (x < img.cols - 1) && (p[x] > p[x + 1])) response[4].at<float>(y, x) = 1.0f;
                if ((x < img.cols - 1) && (p[x] > p[x + 1]) && (p[x] > p_next[x])) response[5].at<float>(y, x) = 1.0f;
                if ((p[x] > p_next[x]) && (x > 0) && (p[x] > p[x - 1])) response[6].at<float>(y, x) = 1.0f;
                if ((x > 0) && (p[x] > p[x - 1]) && (p[x] > p_prev[x])) response[7].at<float>(y, x) = 1.0f;
            }
        }
    }
}
Beispiel #11
0
void BGPattern::maskImage(cv::Mat src, cv::Mat dst)
{
    // accept only char type matrices
    assert(src.depth() == CV_8U && dst.depth() == CV_8U);
    assert(src.channels() == 3 && dst.channels() == 1);
    assert(src.rows == dst.rows && src.cols == dst.cols);
    
    int rows = src.rows, cols = dst.cols;
    int npix = rows * cols;
    uchar *src_data = (uchar*)src.data;
    uchar *dst_data = (uchar*)dst.data;
    
//    for (unsigned int row = 0; row < rows; ++row)
//    {
//        uchar* src_row = src_data + 
//        for (unsigned int col = 0; col < col; ++col)
//    }
    
    double val0[3] = {m_curr[0], m_curr[1], m_curr[2]};
    // find new centroid
    reset();
    /*
    for (unsigned int i = 0; i < npix; ++i )
    {
//        std::cout << (int)src_data[0] << ", " << (int)src_data[1] << ", " << (int)src_data[2] << " " << addPixel(src_data)<< std::endl;
        
        addPixel(src_data);
        
        // move pointers
        src_data += 3;
    }
    computeMean();
    
    src_data = (uchar*)src.data; // reset pointer to beginning of image
    */
    
    for (unsigned int i = 0; i < npix; ++i ) // for next frame...
    {
        if (dist(src_data) < m_dist_th)
            dst_data[0] = 0; // 1 keeps background; 0 keeps objects
        else
            dst_data[0] = 1;
        
        // move pointers
        src_data += 3;
        dst_data += 1;
    }
    computeMean(); // for next frame...
//    std::cout << "center moved: " << dist(val0) << std::endl;
    
}
bool SWSaveKinectData::save(const cv::Mat &oData1, const cv::Mat &oData2)
{
    if(!m_bInit)
    {
        std::cerr << "Error : start must be called before SWSaveKinectData::save. Recording stopped. " << std::endl;
        stop();
        return false;
    }

    if(!(oData1.cols >= 640 && oData1.rows >= 480 && oData2.cols >= 640 && oData2.rows >= 480))
    {
        std::cerr << "Error : parameters mat size SWSaveKinectData::save. Recording stopped. " << std::endl;
        stop();
        return false;
    }

    if(oData1.depth() == CV_8U && oData2.depth() == CV_32F)
    {
        saveVideo(oData1);
        saveCloud(oData2);
    }
    else if(oData1.depth() == CV_32F && oData2.depth() == CV_8U)
    {
        saveVideo(oData2);
        saveCloud(oData1);
    }
    else
    {
        std::cerr << "Error : parameters mat depth SWSaveKinectData::save. Recording stopped. " << std::endl;
        stop();
        return false;
    }

    if(m_dMaxLength < (float)(clock() - m_oProgramTime)/ CLOCKS_PER_SEC)
    {
        std::cout << "Time's up, end of the recording." << std::endl;
        stop();
        return false;
    }

    if(m_dMaxSize <  m_lCurrentTotalSizeWritten / 1000000000.f)
    {
        std::cout << "Allowable size reached, end of the recording. " << std::endl;
        stop();
        return false;
    }

    return true;
}
Beispiel #13
0
void cv_subtractor::set_stddev(const cv::Mat& image, const int depth_code) {
  reset();

  const double f = get_depth_normalizing_factor(image.depth());

  if ((depth_code != CV_32F) && (depth_code != CV_64F)) {
    if (check_if_cv_Mat_is_float_type(image)) {
      image.convertTo(m_img_to_div, image.depth(), f, 0.0);
    } else {
      image.convertTo(m_img_to_div, cv_image_type<lbann::DataType>::T(), f, 0.0);
    }
  } else {
    image.convertTo(m_img_to_div, depth_code, f, 0.0);
  }
}
Beispiel #14
0
QImage imageFromMat(cv::Mat src, QImage::Format format = QImage::Format_Invalid) {
   // By default, preserve the format
   if (format == QImage::Format_Invalid) {
      if (src.channels() == 1)
         format = QImage::Format_Grayscale8;
      else if (src.channels() == 3)
         format = QImage::Format_RGB888;
      else if (src.channels() == 4)
         format = QImage::Format_ARGB32;
   }
   auto data = getConvData(src, format);
   if (!src.data || !src.u || format == QImage::Format_Invalid ||
       data.dst == QImage::Format_Invalid)
      return {};

   QImage dst;
   cv::Mat dstMat_;
   cv::Mat *dstMat = &dstMat;

   bool keepBuffer = false;
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
   keepBuffer = CV_XADD(&src.u->refcount, 0) == 1 // sole reference
         && (src.depth() == CV_8U || src.depth() == CV_8S)
         && src.channels() == data.dstChannels();
   if (keepBuffer) {
      dst = QImage((uchar*)src.data, src.cols, src.rows, src.step, data.dstFormat,
                   [](void *m){ delete static_cast<cv::Mat*>(m); }, new cv::Mat(src));
      dstMat = &src;
   }
#endif
   if (!keepBuffer) {
      dst = QImage(src.cols, src.rows, data.dstFormat);
      dstMat_ = cv::Mat(src.rows, src.cols, data.dstCode, dst.bits(), dst.bytesPerLine());
   }

   cv::Mat depthMat_;
   cv::Mat *depthMat = &depthMat;

   if (src.depth() == CV_8U || src.depth() == CV_8S || src.channels() == data.dstChannels())
      depthMat = &dst;

   double alpha = (src.depth == CV_)
   if (src.depth() != CV_8U)
      src.convertTo(src, CV_8U);


   return dst;
}
Beispiel #15
0
ConnectedComponents::ConnectedComponents( cv::Mat &img ) 
{
  CV_Assert(img.depth() == CV_8U);  // accept only uchar images
  CV_Assert(img.channels() == 1);   // just one channel

  rows = img.rows; 
  cols = img.cols; 
  
  group_t *labels = new group_t [img.cols * img.rows];

  int nrows = img.rows;
  int ncols = img.cols;

  if (img.isContinuous())
  {
    ncols *= nrows;
    nrows = 1;
  }

  // populate label matrix
  int i, j, ct, label = 0; 
  uchar* p;
  for (i = 0; i < nrows; ++i)
  {
    group_t &q = labels[i * img.cols + j]; 
    p = img.ptr<uchar>(i);
    for (j = 0; j < ncols; ++j)
    {
      labels[i * img.cols + j].pixel = p[j];
      labels[i * img.cols + j].label = UNASSIGNED; 
      labels[i * img.cols + j].parent = NULL; 
    }
  }

}
Beispiel #16
0
/** @函数 main */
int myback()
{
    /// 读取图像
//    src = imread( argv[1], 1 );
    /// 转换到 HSV 空间
    cvtColor( src, hsv, CV_BGR2HSV );
    
    /// 分离 Hue 通道
    hue.create( hsv.size(), hsv.depth() );
    int ch[] = { 0, 0 };
    mixChannels( &hsv, 1, &hue, 1, ch, 1 );
    
    /// 创建 Trackbar 来输入bin的数目
    char* window_image = "Source image";
    namedWindow( window_image, CV_WINDOW_AUTOSIZE );
    createTrackbar("* Hue  bins: ", window_image, &bins, 180, Hist_and_Backproj );
    Hist_and_Backproj(0, 0);
    
    /// 现实图像
    imshow( window_image, src );
    
    /// 等待用户反应
    waitKey(0);
    return 0;
}
void ChannelToGreyScale::Process( cv::Mat& srcImage, cv::Mat& destImage )
{
	CV_Assert( srcImage.depth() != sizeof(uchar) );
	CV_Assert( srcImage.rows == destImage.rows );
	CV_Assert( srcImage.cols == destImage.cols );

	switch( srcImage.channels() )
	{
	case 1:
		CV_Assert(false);
	case 3:
		cv::Mat_<cv::Vec3b> source = srcImage;
		cv::Mat_<cv::Vec3b> destination = destImage;

		for ( int i = 0; i < srcImage.rows; ++i )
		{
			for ( int j = 0; j < srcImage.cols; ++j )
			{
				cv::Vec3b lastValue = source( i, j );
				unsigned char color = lastValue[ m_channelNum ];
				destination( i, j ) = cv::Vec3b( color, color, color );
			}
		}

	break;
	}
}
Beispiel #18
0
    bool OpenCVAlgorithms::checkInputImages(const QList<cv::Mat> &sources, const cv::Mat &target)
	{
        foreach(const cv::Mat &source, sources)
        {
            // make sure that the template image is smaller than the source
            if(target.size().width > source.size().width ||
               target.size().height > source.size().height)
            {
                mError = SourceImageSmallerThanTargerImageError;
                mErrorString = tr("Source images must be larger than target image");

                return false;
            }

            if(source.depth() != target.depth())
            {
                mError = NotSameDepthError;
                mErrorString = tr("Source images and target image must have same depth");

                return false;
            }

            if(source.channels() != target.channels())
            {
                mError = NotSameChannelCountError;
                mErrorString = tr("Source images and target image must have same number of channels");

                return false;
            }
        }

		return true;
	}
Beispiel #19
0
MatrixXi drwnMultiSegRegionDefinitions::convertImageToLabels(const cv::Mat& img) const
{
    DRWN_ASSERT((img.channels() == 3) && (img.depth() == CV_8U));

    // build reverse lookup table
    map<unsigned, int> lookup;
    for (map<int, int>::const_iterator it = _keys.begin(); it != _keys.end(); ++it) {
        lookup.insert(make_pair(_colors[it->second], it->first));
    }

    MatrixXi labels = MatrixXi::Constant(img.rows, img.cols, -1);

    for (int y = 0; y < img.rows; y++) {
        const unsigned char *p = img.ptr(y);
        for (int x = 0; x < img.cols; x++) {
            const unsigned colour = this->rgb(p[3*x + 2], p[3*x + 1], p[3*x + 0]);
            map<unsigned, int>::const_iterator it = lookup.find(colour);
            if (it != lookup.end()) {
                labels(y, x) = it->second;
            }
        }
    }

    return labels;
}
void printMatrix(const cv::Mat &arg) {
    std::cerr << "dims: " << arg.cols << ' ' << arg.rows << std::endl;
    std::cerr << "chans: " << arg.channels() << std::endl;
    int type = arg.depth();
    {
        std::string depth;
        switch (type) {
            case CV_8U:
                depth = "CV_8U";
                break;
            case CV_8S:
                depth = "CV_8S";
                break;
            case CV_16U:
                depth = "CV_16U";
                break;
            case CV_16S:
                depth = "CV_16S";
                break;
            case CV_32S:
                depth = "CV_32S";
                break;
            case CV_32F:
                depth = "CV_32F";
                break;
            case CV_64F:
                depth = "CV_64F";
                break;
        }
        std::cerr << "depth: " << depth << std::endl;
    }
}
Beispiel #21
0
 //
 // showPropertiesOfMat
 //
 //   ...displays all properties of specified Mat.
 //
 void showPropertiesOfMat (const cv::Mat &src_mat)
 {
   // 行数
   std::cout << "rows:" << src_mat.rows <<std::endl;
   // 列数
   std::cout << "cols:" << src_mat.cols << std::endl;
   // 次元数
   std::cout << "dims:" << src_mat.dims << std::endl;
   // サイズ(2次元の場合)
   std::cout << "size[]:" << src_mat.size().width << "," << src_mat.size().height  << "[byte]" << std::endl;
   // ビット深度ID
   std::cout << "depth (ID):" << src_mat.depth() << "(=" << CV_64F << ")" << std::endl;
   // チャンネル数
   std::cout << "channels:" << src_mat.channels() << std::endl;
   // 1要素内の1チャンネル分のサイズ [バイト単位]
   std::cout << "elemSize1 (elemSize/channels):" << src_mat.elemSize1() << "[byte]" << std::endl;
   // 要素の総数
   std::cout << "total:" << src_mat.total() << std::endl;
   // ステップ数 [バイト単位]
   std::cout << "step:" << src_mat.step << "[byte]" << std::endl;
   // 1ステップ内のチャンネル総数
   std::cout << "step1 (step/elemSize1):" << src_mat.step1()  << std::endl;
   // データは連続か?
   std::cout << "isContinuous:" << (src_mat.isContinuous()?"true":"false") << std::endl;
   // 部分行列か?
   std::cout << "isSubmatrix:" << (src_mat.isSubmatrix()?"true":"false") << std::endl;
   // データは空か?
   std::cout << "empty:" << (src_mat.empty()?"true":"false") << std::endl;
 }
Beispiel #22
0
void drwnNNGraphImage::appendNodeFeatures(const drwnNNGraphImageData& image, const cv::Mat& features)
{
    DRWN_ASSERT(((int)image.width() == features.cols) && ((int)image.height() == features.rows));
    DRWN_ASSERT(image.numSegments() == this->numNodes());

    // convert to 32-bit floating point (if not already)
    if (features.depth() != CV_32F) {
        cv::Mat tmp(features.rows, features.cols, CV_8U);
        features.convertTo(tmp, CV_32F, 1.0, 0.0);
        return appendNodeFeatures(image, tmp);
    }

    // compute mean pixel feature over each superpixel
    vector<float> phi(image.numSegments(), 0.0f);
    for (unsigned y = 0; y < image.height(); y++) {
        for (unsigned x = 0; x < image.width(); x++) {
            const float p = features.at<float>(y, x);
            for (int c = 0; c < image.segments().channels(); c++) {
                const int segId = image.segments()[c].at<int>(y, x);
                if (segId < 0) continue;

                phi[segId] += p;
            }
        }
    }

    for (unsigned segId = 0; segId < phi.size(); segId++) {
        DRWN_ASSERT(isfinite(phi[segId]));
        VectorXf newFeatures(_nodes[segId].features.rows() + 1);
        newFeatures.head(_nodes[segId].features.rows()) = _nodes[segId].features;
        newFeatures[_nodes[segId].features.rows()] = phi[segId] / (float)image.segments().pixels(segId);
        _nodes[segId].features = newFeatures;
    }
}
Beispiel #23
0
std::vector<unsigned long> create_histogram(const cv::Mat& mat, int channel)
{
	assert(channel >= 0 && channel < mat.channels());
	assert(mat.depth() == CV_8U);

	return create_histogram(mat.data + channel, mat.total(), mat.channels());
}
Beispiel #24
0
cv::Mat im2colstep(cv::Mat& InImg, vector<int>& blockSize, vector<int>& stepSize){
	
	int r_row = blockSize[ROW_DIM] * blockSize[COL_DIM];
	int row_diff = InImg.rows - blockSize[ROW_DIM];
	int col_diff = InImg.cols - blockSize[COL_DIM];
	int r_col = (row_diff / stepSize[ROW_DIM] + 1) * (col_diff / stepSize[COL_DIM] + 1);
	cv::Mat OutBlocks(r_col, r_row, InImg.depth());

	double *p_InImg, *p_OutImg;
	int blocknum = 0;

	for(int j=0; j<=col_diff; j+=stepSize[COL_DIM]){
		for(int i=0; i<=row_diff; i+=stepSize[ROW_DIM]){

			p_OutImg = OutBlocks.ptr<double>(blocknum);
			
			for(int m=0; m<blockSize[ROW_DIM]; m++){
				
				p_InImg = InImg.ptr<double>(i + m);

				for(int l=0; l<blockSize[COL_DIM]; l++){
					p_OutImg[blockSize[ROW_DIM] * l + m] = p_InImg[j + l];
					//p_OutImg[blockSize[COL_DIM] * l + m] = p_InImg[j + l];
				}

			}
			blocknum ++;
		}
	}

	return OutBlocks;
}
Beispiel #25
0
void CVMatToDatum(const cv::Mat& cv_img, Datum* datum) {
  CHECK(cv_img.depth() == CV_8U) << "Image data type must be unsigned byte";
  datum->set_channels(cv_img.channels());
  datum->set_height(cv_img.rows);
  datum->set_width(cv_img.cols);
  datum->clear_data();
  datum->clear_float_data();
  datum->set_encoded(false);
  int datum_channels = datum->channels();
  int datum_height = datum->height();
  int datum_width = datum->width();
  int datum_size = datum_channels * datum_height * datum_width;
  std::string buffer(datum_size, ' ');
  for (int h = 0; h < datum_height; ++h) {
    const uchar* ptr = cv_img.ptr<uchar>(h);
    int img_index = 0;
    for (int w = 0; w < datum_width; ++w) {
      for (int c = 0; c < datum_channels; ++c) {
        int datum_index = (c * datum_height + h) * datum_width + w;
        buffer[datum_index] = static_cast<char>(ptr[img_index++]);
      }
    }
  }
  datum->set_data(buffer);
}
Beispiel #26
0
void my_laplace(cv::Mat& srcImg, cv::Mat& dstImg)
{
    Mat kernel(3,3,CV_32F,Scalar(-1));
    kernel.at<float>(1,1) = 8.9;
    filter2D(srcImg,dstImg,srcImg.depth(),kernel);
    //cvtColor(dstImg, dstImg, CV_RGB2BGR);
}
Beispiel #27
0
void addGaussNoise(cv::Mat& image, double sigma)
{
    cv::Mat noise(image.size(), CV_32FC(image.channels()));
    cvtest::TS::ptr()->get_rng().fill(noise, cv::RNG::NORMAL, 0.0, sigma);

    cv::addWeighted(image, 1.0, noise, 1.0, 0.0, image, image.depth());
}
Beispiel #28
0
void TreeLiveProc::process (const cv::Mat& dmap,
                            cv::Mat&       lmap )
{
	if( dmap.depth()       != CV_16U ) TLIVEEXCEPT("depth has incorrect channel type")
	if( dmap.channels()    != 1 )      TLIVEEXCEPT("depth has incorrect channel count")
	if( dmap.size().width  != 640 )    TLIVEEXCEPT("depth has incorrect width")
	if( dmap.size().height != 480 )    TLIVEEXCEPT("depth has incorrect height")
	if( !dmap.isContinuous() )         TLIVEEXCEPT("depth has non contiguous rows")

	// alloc the buffer if it isn't done yet
	lmap.create( 480, 640, CV_8UC(1) );
	
	// copy depth to cuda
	cudaMemcpy(m_dmap_device, (const void*) dmap.data, 
	                          640*480*sizeof(uint16_t), cudaMemcpyHostToDevice);
	// process the dmap
	CUDA_runTree( 640,480, focal, 
	              m_tree->treeHeight(), 
	              m_tree->numNodes(), 
	              m_tree->nodes_device(), 
	              m_tree->leaves_device(),
	              m_dmap_device, 
	              m_lmap_device );
	// download back from cuda
	cudaMemcpy((Label*)(lmap.data), m_lmap_device,
	                             640*480*sizeof(Label), cudaMemcpyDeviceToHost);
}
Beispiel #29
0
void GLImageView::setImage(const cv::Mat& frame) {
    switch (frame.channels()) {
	case 1:
        format = GL_LUMINANCE;
		break;
	case 2:
		format = GL_LUMINANCE_ALPHA;
		break;
	case 3:
		format = GL_BGR;
		break;
	case 4:
		format = GL_BGRA;
		break;
	default:
		return;
	}
    switch (frame.depth()) {
    case CV_8U:
        depth = GL_UNSIGNED_BYTE;
        break;
    case CV_16U:
        depth = GL_UNSIGNED_SHORT;
        break;
    default:
        return;
    }
    cv::Size oldsize = cv_frame.size();
    cv_frame = frame;
    if (cv_frame.size() != oldsize) updateGeometry();
    update();
}
Beispiel #30
0
inline std::vector<cv::Mat_<T>> decoupage(const cv::Mat& oImage) 
{
	CV_Assert(oImage.depth()==CV_8U);

	int nbBlocbycols = oImage.cols/ 8; // nombre de bloc par colonne
	int nbBlocbyrows = oImage.rows / 8;// nombre de bloc par ligne
	std::vector<cv::Mat_<T>> blocMat(nbBlocbycols * nbBlocbyrows *oImage.channels());
	std::vector<cv::Mat_<T>> rgbChannels(oImage.channels());
	
	if (oImage.channels() == 1)
	{
		rgbChannels[0] = oImage;
	}
	else
	{
		cv::split(oImage, rgbChannels);
	}

	for (int c = 0; c < rgbChannels.size(); ++c)
	{
		for (int i = 0; i<nbBlocbyrows; ++i) 
		{
			for (int j = 0; j<nbBlocbycols; ++j) 
			{
				blocMat[c*nbBlocbyrows *nbBlocbycols + i * nbBlocbycols + j] = rgbChannels[c].cv::Mat::colRange(j * 8, (j + 1) * 8).cv::Mat::rowRange(i * 8, (i + 1) * 8);
			}
		}
	}

	return blocMat;
}