当前位置: 首页>>代码示例>>C++>>正文


C++ Mat::convertTo方法代码示例

本文整理汇总了C++中Mat::convertTo方法的典型用法代码示例。如果您正苦于以下问题:C++ Mat::convertTo方法的具体用法?C++ Mat::convertTo怎么用?C++ Mat::convertTo使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Mat的用法示例。


在下文中一共展示了Mat::convertTo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: fillData

JNIEXPORT jintArray JNICALL Java_com_example_uemcar_Camera_FindFeatures(JNIEnv *env, jclass cls,
                                                                   jlong frame, jint mode) {
    /**
     * Leer los datos de entrenamiento una sola vez
     * Configurar el modelo KNN
     */
    if (trained == 0) {
        fillData();
        trainingData = TrainData::create(sample, SampleTypes::ROW_SAMPLE, response);
        knn->setIsClassifier(true);
        knn->setAlgorithmType(KNearest::Types::BRUTE_FORCE);
        knn->setDefaultK(1);
        knn->train(trainingData); // Train with sample and responses
        trained = 1;
    }

    /**
     * Preparación para devolver un array de 5 ints
     * https://stackoverflow.com/questions/1610045/how-to-return-an-array-from-jni-to-java
     */
    jintArray result;
    result = (env)->NewIntArray(5);
    if (result == NULL)
        return NULL; /* out of memory error thrown */
    jint fill[256];
    int numSe = 0;
    for(int i = 0; i < 5; i++)
        fill[i] = 1;

    // Frame de la camara pasada desde el JNI
    Mat &src = *(Mat *) frame;  // Formato RGB!! (por defecto OpenCV usa BGR)
    Mat originalSrc;
    src.copyTo(originalSrc);

    // CLAHE demasiado lento - ajuste dinamico??

    // Erode & Dilate quita muchos puntos innecesarios
    erode(src, src, Mat());
    dilate(src, src, Mat());

    // Pasar a HSV
    Mat mHSV, mHSV2;
    cvtColor(src, mHSV, COLOR_RGB2HSV);
    mHSV.copyTo(mHSV2);

    // Regiones rojas
    cv::Mat mRedHue;
    cv::Mat lower_red_hue_range;
    cv::Mat upper_red_hue_range;
    cv::inRange(mHSV, cv::Scalar(0, 100, 100), cv::Scalar(10, 255, 255), lower_red_hue_range);
    cv::inRange(mHSV, cv::Scalar(160, 100, 100), cv::Scalar(179, 255, 255), upper_red_hue_range);

    // Gaussian blur
    cv::addWeighted(lower_red_hue_range, 1.0, upper_red_hue_range, 1.0, 0.0, mRedHue);
    cv::GaussianBlur(mRedHue, mRedHue, cv::Size(9, 9), 2, 2);
    Mat mRedHue2;
    mRedHue.copyTo(mRedHue2);

    // Extraer contornos (blobs) usando Canny y findContours
    std::vector<std::vector<cv::Point> > contours;
    vector< Vec4i > hierarchy;
    Canny(mRedHue, mRedHue, 10, 25, 3);
    cv::findContours(mRedHue, contours, hierarchy,
                     CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));

    // Recorrer todos los contornos con nivel jerárquico 0
    for (int i = 0; i < contours.size(); i = hierarchy[i][0]) {
        //approxPolyDP para el STOP?

        Rect r = boundingRect(contours[i]);
        Mat ROI = src(r);

        // Comprobar tamaño y ratio - si es demasiado pequeño salir de iteración
        if ((ROI.cols > 2* ROI.rows) || (ROI.rows > ROI.cols*2 ) || ROI.cols < 20 || ROI.rows < 20)
            continue;

        // Dibujar circulos en Mat
        drawContours(src, contours, -1, Scalar(0, 255, 0));

        std::vector<cv::Vec3f> circles;
        Mat ROIg;

        // Detectar circulos
        cvtColor(ROI, ROIg, CV_RGB2GRAY); // HoughCircles acepta solo imagenes en escala de grises
        // Param2 deberia ser relativo al tamaño del ROI (2*3.14*ROI.rows*porcentajePtos)
        cv::HoughCircles(ROIg, circles, CV_HOUGH_GRADIENT, 1, ROIg.rows, 200, 60, 25, 360);

        // Dibujar circulos en Mat
        for (Vec3f c : circles)
            circle(ROI, Point(c[0], c[1]), c[2], Scalar(0, 255, 0));

        // Analizar blob si hemos encontrado por lo menos un circulo
        if (circles.size() != 0) {
            Mat tmp;
            resize(ROIg, tmp, Size(50, 50), 0, 0, INTER_LINEAR);  // Normalizar a 50x50
            tmp.convertTo(tmp, CV_32FC1);  // Convertir a coma flotante

            // Comprarar usando KNN
            int found = knn->findNearest(tmp.reshape(1, 1), knn->getDefaultK(), tmp);

//.........这里部分代码省略.........
开发者ID:hugo19941994,项目名称:InfracCoche,代码行数:101,代码来源:jniPart.cpp

示例2: main

int main(int argc, char *argv[])
{
  	//KALMAN
  	measurement.setTo(Scalar(0));
  	measurement = Mat_<float>(2,1); 
  	KFrightEye = KalmanFilter(4, 2, 0);
  	KFleftEye = KalmanFilter(4, 2, 0);
  	state = Mat_<float>(4, 1); 
  	processNoise = Mat(4, 1, CV_32F);
  	// Reconhecimento continuo
  	float P_Safe_Ultimo = 1.0, P_notSafe_Ultimo = 0.0;
  	float P_Atual_Safe, P_Atual_notSafe;
  	float P_Safe_Atual, P_notSafe_Atual;
  	float P_Safe;
  	float timeLastObs = 0, timeAtualObs = 0, tempo = 0;
    // These vectors hold the images and corresponding labels:
    vector<Mat> images;
    vector<Mat> video;
    vector<int> labels;
    // Create a FaceRecognizer and train it on the given images:
    Ptr<FaceRecognizer> model = createLBPHFaceRecognizer();
    //leitura dos frames
    STREAM *ir = createStream("../build/ir.log");
    bool flag_ir;
    flag_ir = streamNext(ir);
    struct timeval now;
    gettimeofday(&now, NULL);
    
    CascadeClassifier haar_cascade;
    haar_cascade.load(PATH_CASCADE_FACE);
    bool sucess = false;
    int login = 0;
    Point ultimaFace = Point(-1, -1);
    
    while(flag_ir) {
    	  Mat frame = ir->infrared;
        frame.convertTo(frame, CV_8UC3, 255, 0);
        vector< Rect_<int> > faces;
        // Find the faces in the frame:
        haar_cascade.detectMultiScale(frame, faces);
        tempo = getTickCount();
        for(int j = 0; j < faces.size(); j++) {
         	    Mat face = frame(faces[j]);
		    Rect faceRect = faces[j];
		    Point center = Point(faceRect.x + faceRect.width/2, faceRect.y + faceRect.width/2);
		    if(ultimaFace.x < 0) {
		    		ultimaFace.x = center.x;
		    		ultimaFace.y = center.y;
		    }
		    else {
		    		double res = cv::norm(ultimaFace-center);
		    		if(res < 50.0) {
		    			ultimaFace.x = center.x;
			    		ultimaFace.y = center.y;
			    		Mat faceNormalized = faceNormalize(face, FACE_SIZE, sucess);
			          if(sucess) {
			                if(login < FRAMES_LOGIN) {
			                  images.push_back(faceNormalized);
			                  labels.push_back(0);
			                  login++;
			                  if(login == FRAMES_LOGIN) 
			                    model->train(images, labels);
			                }
			                else {
			                    timeLastObs= timeAtualObs;
			                    timeAtualObs = tempo;
			                    double confidence;
			                    int prediction;
			                    model->predict(faceNormalized, prediction, confidence);
			                    //reconhecimento continuo
			                    if(timeLastObs == 0) {
			                    	P_Atual_Safe = 1 - ((1 + erf((confidence-Usafe) / (Rsafe*sqrt(2))))/2);
			                    	P_Atual_notSafe = ((1 + erf((confidence-UnotSafe) / (RnotSafe*sqrt(2))))/2);
			                        float deltaT = (timeLastObs - timeAtualObs)/getTickFrequency();
			                        float elevado = (deltaT * LN2)/K_DROP;
			                    	P_Safe_Atual = P_Atual_Safe + pow(E,elevado) * P_Safe_Ultimo;
			              		    P_notSafe_Atual = P_Atual_notSafe + pow(E,elevado) * P_notSafe_Ultimo;
			                    }
			                    else {
			                    	P_Atual_Safe = 1 - ((1 + erf((confidence-Usafe) / (Rsafe*sqrt(2))))/2);
			                    	P_Atual_notSafe = ((1 + erf((confidence-UnotSafe) / (RnotSafe*sqrt(2))))/2);
			                    	P_Safe_Ultimo = P_Safe_Atual;
			                    	P_notSafe_Ultimo = P_notSafe_Atual;
			                    	float deltaT = (timeLastObs - timeAtualObs)/getTickFrequency();
			                      float elevado = (deltaT * LN2)/K_DROP;
			                      P_Safe_Atual = P_Atual_Safe + pow(E,elevado) * P_Safe_Ultimo;
			                      P_notSafe_Atual = P_Atual_notSafe + pow(E,elevado) * P_notSafe_Ultimo;
			                    }
			                }
			            }
				 }
		    }
        }
        if(P_Safe_Atual != 0) {
          float deltaT = -(tempo - timeAtualObs)/getTickFrequency();
          float elevado = (deltaT * LN2)/K_DROP;
          P_Safe = (pow(E,elevado) * P_Safe_Atual)/(P_Safe_Atual+P_notSafe_Atual);
          if(P_Safe > 0)
            cout << P_Safe << endl;
        }
//.........这里部分代码省略.........
开发者ID:TheusStremens,项目名称:IniciacaoCientifica,代码行数:101,代码来源:Aut_Cont_NIR_Dump.cpp

示例3: GetSal

Mat GMRsaliency::GetSal(Mat &img)
{

	int wcut[6];
	img=RemoveFrame(img,wcut);
	Mat suplabel(img.size(),CV_16U);
	suplabel=GetSup(img);

	Mat adj(Size(spcounta,spcounta),CV_16U);
	adj=GetAdjLoop(suplabel);

	Mat tImg;
	img.convertTo(tImg,CV_32FC3,1.0/255);
	cvtColor(tImg, tImg, CV_BGR2Lab);

	Mat W(adj.size(),CV_32F);
	W=GetWeight(tImg,suplabel,adj);

	Mat optAff(W.size(),CV_32F);
	optAff=GetOptAff(W);

	Mat salt,sald,sall,salr;
	Mat bdy;

	bdy=GetBdQuery(suplabel,1);
	salt=optAff*bdy;
	normalize(salt, salt, 0, 1, NORM_MINMAX);
	salt=1-salt;

	bdy=GetBdQuery(suplabel,2);
	sald=optAff*bdy;
	normalize(sald, sald, 0, 1, NORM_MINMAX);
	sald=1-sald;

	bdy=GetBdQuery(suplabel,3);
	sall=optAff*bdy;
	normalize(sall, sall, 0, 1, NORM_MINMAX);
	sall=1-sall;

	bdy=GetBdQuery(suplabel,4);
	salr=optAff*bdy;
	normalize(salr, salr, 0, 1, NORM_MINMAX);
	salr=1-salr;

	Mat salb;
	salb=salt;
	salb=salb.mul(sald);
	salb=salb.mul(sall);
	salb=salb.mul(salr);

	double thr=mean(salb)[0];
	Mat fgy;
	threshold(salb,fgy,thr,1,THRESH_BINARY);

  Mat salf;
	salf=optAff*fgy;

	Mat salMap(img.size(),CV_32F);
	for(int i=0;i<salMap.rows;i++)
	{
		for(int j=0;j<salMap.cols;j++)
		{
			salMap.at<float>(i,j)=salf.at<float>(suplabel.at<ushort>(i,j));
		}
	}

	normalize(salMap, salMap, 0, 1, NORM_MINMAX);

	Mat outMap(Size(wcut[1],wcut[0]),CV_32F,Scalar(0));
	Mat subMap=outMap(Range(wcut[2],wcut[3]),Range(wcut[4],wcut[5]));
	salMap.convertTo(subMap,subMap.type());
	return outMap;

}
开发者ID:GabiThume,项目名称:msc-src,代码行数:74,代码来源:GMRsaliency.cpp

示例4: findConstrainedCorrespondences

static void findConstrainedCorrespondences(const Mat& _F,
                const vector<KeyPoint>& keypoints1,
                const vector<KeyPoint>& keypoints2,
                const Mat& descriptors1,
                const Mat& descriptors2,
                vector<Vec2i>& matches,
                double eps, double ratio)
{
    float F[9]={0};
    int dsize = descriptors1.cols;

    Mat Fhdr = Mat(3, 3, CV_32F, F);
    _F.convertTo(Fhdr, CV_32F);
    matches.clear();

    for( int i = 0; i < (int)keypoints1.size(); i++ )
    {
        Point2f p1 = keypoints1[i].pt;
        double bestDist1 = DBL_MAX, bestDist2 = DBL_MAX;
        int bestIdx1 = -1;//, bestIdx2 = -1;
        const float* d1 = descriptors1.ptr<float>(i);

        for( int j = 0; j < (int)keypoints2.size(); j++ )
        {
            Point2f p2 = keypoints2[j].pt;
            double e = p2.x*(F[0]*p1.x + F[1]*p1.y + F[2]) +
                       p2.y*(F[3]*p1.x + F[4]*p1.y + F[5]) +
                       F[6]*p1.x + F[7]*p1.y + F[8];
            if( fabs(e) > eps )
                continue;
            const float* d2 = descriptors2.ptr<float>(j);
            double dist = 0;
            int k = 0;

            for( ; k <= dsize - 8; k += 8 )
            {
                float t0 = d1[k] - d2[k], t1 = d1[k+1] - d2[k+1];
                float t2 = d1[k+2] - d2[k+2], t3 = d1[k+3] - d2[k+3];
                float t4 = d1[k+4] - d2[k+4], t5 = d1[k+5] - d2[k+5];
                float t6 = d1[k+6] - d2[k+6], t7 = d1[k+7] - d2[k+7];
                dist += t0*t0 + t1*t1 + t2*t2 + t3*t3 +
                        t4*t4 + t5*t5 + t6*t6 + t7*t7;

                if( dist >= bestDist2 )
                    break;
            }

            if( dist < bestDist2 )
            {
                for( ; k < dsize; k++ )
                {
                    float t = d1[k] - d2[k];
                    dist += t*t;
                }

                if( dist < bestDist1 )
                {
                    bestDist2 = bestDist1;
                    //bestIdx2 = bestIdx1;
                    bestDist1 = dist;
                    bestIdx1 = (int)j;
                }
                else if( dist < bestDist2 )
                {
                    bestDist2 = dist;
                    //bestIdx2 = (int)j;
                }
            }
        }

        if( bestIdx1 >= 0 && bestDist1 < bestDist2*ratio )
        {
            Point2f p2 = keypoints1[bestIdx1].pt;
            double e = p2.x*(F[0]*p1.x + F[1]*p1.y + F[2]) +
                        p2.y*(F[3]*p1.x + F[4]*p1.y + F[5]) +
                        F[6]*p1.x + F[7]*p1.y + F[8];
            if( e > eps*0.25 )
                continue;
            double threshold = bestDist1/ratio;
            const float* d22 = descriptors2.ptr<float>(bestIdx1);
            int i1 = 0;
            for( ; i1 < (int)keypoints1.size(); i1++ )
            {
                if( i1 == i )
                    continue;
                Point2f pt1 = keypoints1[i1].pt;
                const float* d11 = descriptors1.ptr<float>(i1);
                double dist = 0;

                e = p2.x*(F[0]*pt1.x + F[1]*pt1.y + F[2]) +
                    p2.y*(F[3]*pt1.x + F[4]*pt1.y + F[5]) +
                    F[6]*pt1.x + F[7]*pt1.y + F[8];
                if( fabs(e) > eps )
                    continue;

                for( int k = 0; k < dsize; k++ )
                {
                    float t = d11[k] - d22[k];
                    dist += t*t;
                    if( dist >= threshold )
//.........这里部分代码省略.........
开发者ID:BroboticsForever,项目名称:ComputerVision,代码行数:101,代码来源:build3dmodel.cpp

示例5: main

int main(int argc, char **argv)
{
	//Read a single-channel image
	const char* filename = "imageText.jpg";
	Mat srcImg = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
	if(srcImg.empty())
		return -1;
	imshow("source", srcImg);

	Point center(srcImg.cols/2, srcImg.rows/2);

#ifdef DEGREE
	//Rotate source image
	Mat rotMatS = getRotationMatrix2D(center, DEGREE, 1.0);
	warpAffine(srcImg, srcImg, rotMatS, srcImg.size(), 1, 0, Scalar(255,255,255));
	imshow("RotatedSrc", srcImg);
	//imwrite("imageText_R.jpg",srcImg);
#endif

	//Expand image to an optimal size, for faster processing speed
	//Set widths of borders in four directions
	//If borderType==BORDER_CONSTANT, fill the borders with (0,0,0)
	Mat padded;
	int opWidth = getOptimalDFTSize(srcImg.rows);
	int opHeight = getOptimalDFTSize(srcImg.cols);
	copyMakeBorder(srcImg, padded, 0, opWidth-srcImg.rows, 0, opHeight-srcImg.cols, BORDER_CONSTANT, Scalar::all(0));

	Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
	Mat comImg;
	//Merge into a double-channel image
	merge(planes,2,comImg);

	//Use the same image as input and output,
	//so that the results can fit in Mat well
	dft(comImg, comImg);

	//Compute the magnitude
	//planes[0]=Re(DFT(I)), planes[1]=Im(DFT(I))
	//magnitude=sqrt(Re^2+Im^2)
	split(comImg, planes);
	magnitude(planes[0], planes[1], planes[0]);

	//Switch to logarithmic scale, for better visual results
	//M2=log(1+M1)
	Mat magMat = planes[0];
	magMat += Scalar::all(1);
	log(magMat, magMat);

	//Crop the spectrum
	//Width and height of magMat should be even, so that they can be divided by 2
	//-2 is 11111110 in binary system, operator & make sure width and height are always even
	magMat = magMat(Rect(0, 0, magMat.cols & -2, magMat.rows & -2));

	//Rearrange the quadrants of Fourier image,
	//so that the origin is at the center of image,
	//and move the high frequency to the corners
	int cx = magMat.cols/2;
	int cy = magMat.rows/2;

	Mat q0(magMat, Rect(0, 0, cx, cy));
	Mat q1(magMat, Rect(0, cy, cx, cy));
	Mat q2(magMat, Rect(cx, cy, cx, cy));
	Mat q3(magMat, Rect(cx, 0, cx, cy));

	Mat tmp;
	q0.copyTo(tmp);
	q2.copyTo(q0);
	tmp.copyTo(q2);

	q1.copyTo(tmp);
	q3.copyTo(q1);
	tmp.copyTo(q3);

	//Normalize the magnitude to [0,1], then to[0,255]
	normalize(magMat, magMat, 0, 1, CV_MINMAX);
	Mat magImg(magMat.size(), CV_8UC1);
	magMat.convertTo(magImg,CV_8UC1,255,0);
	imshow("magnitude", magImg);
	//imwrite("imageText_mag.jpg",magImg);

	//Turn into binary image
	threshold(magImg,magImg,GRAY_THRESH,255,CV_THRESH_BINARY);
	imshow("mag_binary", magImg);
	//imwrite("imageText_bin.jpg",magImg);

	//Find lines with Hough Transformation
	vector<Vec2f> lines;
	float pi180 = (float)CV_PI/180;
	Mat linImg(magImg.size(),CV_8UC3);
	HoughLines(magImg,lines,1,pi180,HOUGH_VOTE,0,0);
	int numLines = lines.size();
	for(int l=0; l<numLines; l++)
	{
		float rho = lines[l][0], theta = lines[l][1];
		Point pt1, pt2;
		double a = cos(theta), b = sin(theta);
		double x0 = a*rho, y0 = b*rho;
		pt1.x = cvRound(x0 + 1000*(-b));
		pt1.y = cvRound(y0 + 1000*(a));
		pt2.x = cvRound(x0 - 1000*(-b));
//.........这里部分代码省略.........
开发者ID:bolghuar,项目名称:textRotCorrect,代码行数:101,代码来源:textRotCorrect.cpp

示例6: colorSpaceAnalysis

 void colorSpaceAnalysis( Mat frameBGR, CvSize size )
 {	
	IplImage *t1 = cvCreateImage( size, IPL_DEPTH_8U, 3 );
	IplImage *t2 = cvCreateImage( size, IPL_DEPTH_8U, 1 );
	IplImage *t3 = cvCreateImage( size, IPL_DEPTH_8U, 1 );
	IplImage *t4 = cvCreateImage( size, IPL_DEPTH_8U, 1 );
	IplImage *t5 = cvCreateImage( size, IPL_DEPTH_16S, 1 );
	IplImage *t6 = cvCreateImage( size, IPL_DEPTH_8U, 1 );
	IplImage *t7 = cvCreateImage( size, IPL_DEPTH_16S, 1 );
	IplImage *t8 = cvCreateImage( size, IPL_DEPTH_8U, 1 );
	IplImage *t9 = cvCreateImage( size, IPL_DEPTH_16S, 1 );
	IplImage *t0 = cvCreateImage( size, IPL_DEPTH_8U, 1 );
	IplImage *tA = cvCreateImage( size, IPL_DEPTH_16S, 1 );
	IplImage *tB = cvCreateImage( size, IPL_DEPTH_8U, 1 );
	IplImage *tC = cvCreateImage( size, IPL_DEPTH_16S, 1 );
	IplImage *tD = cvCreateImage( size, IPL_DEPTH_8U, 1 );
	IplImage *tE = cvCreateImage( size, IPL_DEPTH_16S, 1 );
	IplImage *tF = cvCreateImage( size, IPL_DEPTH_8U, 1 );

	unsigned char new_pixel[8][3] = {
		{ 0, 0, 0 },
		{ 0, 255, 255 },
		{ 255, 255, 0 },
		{ 255, 0, 255 },
		{ 255, 0, 0 },
		{ 0, 255, 0 },
		{ 0, 0, 255 },
		{ 255, 255, 255 } };

	Mat frame2 = frameBGR;
	Mat frameXYZ;
	Mat frameYBR;
	Mat frameHSV;
	Mat frameHLS;
	Mat frameLAB;
	Mat frameLUV;
	IplImage* result = cvCreateImage( size, IPL_DEPTH_8U, 3 );
	IplImage* resultXYZ = cvCreateImage( size, IPL_DEPTH_8U, 3 );
	IplImage* resultYBR = cvCreateImage( size, IPL_DEPTH_8U, 3 );
	IplImage* resultHSV = cvCreateImage( size, IPL_DEPTH_8U, 3 );
	IplImage* resultHLS = cvCreateImage( size, IPL_DEPTH_8U, 3 );
	IplImage* resultLAB = cvCreateImage( size, IPL_DEPTH_8U, 3 );
	IplImage* resultLUV = cvCreateImage( size, IPL_DEPTH_8U, 3 );

	int cluster_count = 4;
	cvtColor( frameBGR, frameXYZ, CV_BGR2XYZ, 0 );
	cvtColor( frameBGR, frameYBR, CV_BGR2YCrCb, 0 );
	cvtColor( frameBGR, frameHSV, CV_BGR2HSV, 0 );
	cvtColor( frameBGR, frameHLS, CV_BGR2HLS, 0 );
	cvtColor( frameBGR, frameLAB, CV_BGR2Lab, 0 );
	cvtColor( frameBGR, frameLUV, CV_BGR2Luv, 0 );

		
	Mat points = frameBGR.reshape( 1, frameBGR.cols*frameBGR.rows );
	//Mat points = frame2.reshape( 1, frame2.cols*frame2.rows );
	Mat clusters, centers;
	points.convertTo(points, CV_32FC3, 1.0/255.0);
	Mat pointsXYZ = frameXYZ.reshape( 1, size.height*size.width );
	//pointsXYZ = pointsXYZ.colRange(0, 1);
	Mat clustersXYZ, centersXYZ;
	pointsXYZ.convertTo(pointsXYZ, CV_32FC3, 1.0/255.0);
	Mat pointsYBR = frameYBR.reshape( 1, size.height*size.width );
	//pointsYBR = pointsYBR.col(0);
	Mat clustersYBR, centersYBR;
	pointsYBR.convertTo(pointsYBR, CV_32FC3, 1.0/255.0);
	Mat pointsHSV = frameHSV.reshape( 1, size.height*size.width );
	//pointsHSV = pointsHSV.colRange( 0, 1 );
	Mat clustersHSV, centersHSV;
	pointsHSV.convertTo(pointsHSV, CV_32FC3, 1.0/255.0);
	Mat pointsHLS = frameHLS.reshape( 1, size.height*size.width );
	//pointsHLS = pointsHLS.colRange( 0, 1 );
	Mat clustersHLS, centersHLS;
	pointsHLS.convertTo(pointsHLS, CV_32FC3, 1.0/255.0);
	Mat pointsLAB = frameLAB.reshape( 1, size.height*size.width );
	//pointsLAB = pointsLAB.col(0);
	Mat clustersLAB, centersLAB;
	pointsLAB.convertTo(pointsLAB, CV_32FC3, 1.0/255.0);
	Mat pointsLUV = frameLUV.reshape( 1, size.height*size.width );
	//pointsLUV = pointsLUV.col(0);
	Mat clustersLUV, centersLUV;
	pointsLUV.convertTo(pointsLUV, CV_32FC3, 1.0/255.0);


	kmeans( points, cluster_count, clusters,
		TermCriteria( CV_TERMCRIT_ITER, 1, 10.0 ),
		1, KMEANS_RANDOM_CENTERS, centers );
	kmeans( pointsXYZ, cluster_count, clustersXYZ,
		TermCriteria( CV_TERMCRIT_ITER, 1, 10.0 ),
		1, KMEANS_RANDOM_CENTERS, centers );
	kmeans( pointsYBR, cluster_count, clustersYBR,
		TermCriteria( CV_TERMCRIT_ITER, 1, 10.0 ),
		1, KMEANS_RANDOM_CENTERS, centers );
	kmeans( pointsHSV, cluster_count, clustersHSV,
		TermCriteria( CV_TERMCRIT_ITER, 1, 10.0 ),
		1, KMEANS_RANDOM_CENTERS, centers );
	kmeans( pointsHLS, cluster_count, clustersHLS,
		TermCriteria( CV_TERMCRIT_ITER, 1, 10.0 ),
		1, KMEANS_RANDOM_CENTERS, centers );
	kmeans( pointsLAB, cluster_count, clustersLAB,
		TermCriteria( CV_TERMCRIT_ITER, 1, 10.0 ),
//.........这里部分代码省略.........
开发者ID:LeArmadillo,项目名称:Code,代码行数:101,代码来源:W6_UT_GE_22.cpp

示例7: main

int main( int argc, char** argv )
{
    printf( "Scale Space Cost Aggregation\n" );
    if( argc != 11 ) {
        printf( "Usage: [CC_METHOD] [CA_METHOD] [PP_METHOD] [C_ALPHA] [lImg] [rImg] [lDis] [rDis] [maxDis] [disSc]\n" );
        printf( "\nPress any key to continue...\n" );
        getchar();
        return -1;
    }
    string ccName = argv[ 1 ];
    string caName = argv[ 2 ];
    string ppName = argv[ 3 ];
    double costAlpha = atof( argv[ 4 ] );
    string lFn = argv[ 5 ];
    string rFn = argv[ 6 ];
    string lDisFn = argv[ 7 ];
    string rDisFn = argv[ 8 ];
    int maxDis = atoi( argv[ 9 ] );
    int disSc  = atoi( argv[ 10 ] );
    //
    // Load left right image
    //
    printf( "\n--------------------------------------------------------\n" );
    printf( "Load Image: (%s) (%s)\n", argv[ 5 ], argv[ 6 ] );
    printf( "--------------------------------------------------------\n" );
    Mat lImg = imread( lFn, CV_LOAD_IMAGE_COLOR );
    Mat rImg = imread( rFn, CV_LOAD_IMAGE_COLOR );
    if( !lImg.data || !rImg.data ) {
        printf( "Error: can not open image\n" );
        printf( "\nPress any key to continue...\n" );
        getchar();
        return -1;
    }
    // set image format
    cvtColor( lImg, lImg, CV_BGR2RGB );
    cvtColor( rImg, rImg, CV_BGR2RGB );
    lImg.convertTo( lImg, CV_64F, 1 / 255.0f );
    rImg.convertTo( rImg, CV_64F,  1 / 255.0f );

    // time
    double duration;
    duration = static_cast<double>(getTickCount());

    //
    // Stereo Match at each pyramid
    //
    int PY_LVL = 5;
    // build pyramid and cost volume
    Mat lP = lImg.clone();
    Mat rP = rImg.clone();
    SSCA** smPyr = new SSCA*[ PY_LVL ];
    CCMethod* ccMtd = getCCType( ccName );
    CAMethod* caMtd = getCAType( caName );
    PPMethod* ppMtd = getPPType( ppName );
    for( int p = 0; p < PY_LVL; p ++ ) {
        if( maxDis < 5 ) {
            PY_LVL = p;
            break;
        }
        printf( "\n\tPyramid: %d:", p );
        smPyr[ p ] = new SSCA( lP, rP, maxDis, disSc );


        smPyr[ p ]->CostCompute( ccMtd );

        smPyr[ p ]->CostAggre( caMtd  );
        // pyramid downsample
        maxDis = maxDis / 2 + 1;
        disSc  *= 2;
        pyrDown( lP, lP );
        pyrDown( rP, rP );
    }
    printf( "\n--------------------------------------------------------\n" );
    printf( "\n Cost Aggregation in Scale Space\n" );
    printf( "\n--------------------------------------------------------\n" );
    // new method
    SolveAll( smPyr, PY_LVL, costAlpha );

    // old method
    //for( int p = PY_LVL - 2 ; p >= 0; p -- ) {
    //	smPyr[ p ]->AddPyrCostVol( smPyr[ p + 1 ], costAlpha );
    //}

    //
    // Match + Postprocess
    //
    smPyr[ 0 ]->Match();
    smPyr[ 0 ]->PostProcess( ppMtd );
    Mat lDis = smPyr[ 0 ]->getLDis();
    Mat rDis = smPyr[ 0 ]->getRDis();
#ifdef _DEBUG
    for( int s = 0; s < PY_LVL; s ++ ) {
        smPyr[ s ]->Match();
        Mat sDis = smPyr[ s ]->getLDis();
        ostringstream sStr;
        sStr << s;
        string sFn = sStr.str( ) + "_ld.png";
        imwrite( sFn, sDis );
    }
    saveOnePixCost( smPyr, PY_LVL );
//.........这里部分代码省略.........
开发者ID:samlong-yang,项目名称:CrossScaleStereo,代码行数:101,代码来源:main.cpp

示例8: ShowImage

void ShowImage(Mat image,int type,string WindowName)
{
    namedWindow( WindowName, WINDOW_AUTOSIZE );// Create a window for display.
    image.convertTo(image,type);
    imshow( WindowName, image);
}
开发者ID:Ethan-Zhou,项目名称:RobustDenseVO,代码行数:6,代码来源:TestFuncs.cpp

示例9: HandPixel

  void HandPixel(Mat depth, Mat RGB,Mat Mask, float dis,float dis2, int it,String name){
    const float bad_point = std::numeric_limits<float>::quiet_NaN();
 	pcl::PointCloud<pcl::PointXYZRGB>::Ptr nube(new pcl::PointCloud<pcl::PointXYZRGB>);
	pcl::PointCloud<pcl::PointXYZRGB>::Ptr nubef(new pcl::PointCloud<pcl::PointXYZRGB>);
	pcl::PointCloud<pcl::PointXYZRGB>::Ptr nubef2(new pcl::PointCloud<pcl::PointXYZRGB>);
	pcl::PointCloud<pcl::PointXYZRGB>::Ptr nubef3(new pcl::PointCloud<pcl::PointXYZRGB>);
 	pcl::PointCloud<pcl::PointXYZRGB>::Ptr nube2(new pcl::PointCloud<pcl::PointXYZRGB>);
	pcl::PointCloud<pcl::PointXYZ>::Ptr nubep(new pcl::PointCloud<pcl::PointXYZ>);
	Mat Ultima = RGB.clone();
    Mat Depth2 = depth.clone();
	Mat inpaintMask = Mat::zeros(RGB.size(), CV_8U);
    uint16_t b = depth.at<uint16_t>(0,0);
    for(int i = 0; i < Ultima.rows; i++)
      {
      for(int j = 0; j < Ultima.cols; j++)
        {
        	uint16_t x = depth.at<uint16_t>(i,j);
			if (x == b){
				inpaintMask.at<uint8_t>(i,j) = 1;
				}
		}
	}
    int Hist[640]={};
    Mat d = depth;
    d.convertTo(d, CV_8U,1.0/256, 0);
	int min = 1000000;
	int max = 0;
    //inpaint(d, inpaintMask, Depth2, 1, INPAINT_TELEA);
    imwrite("Depth.png",Depth2);	
    uint8_t black = depth.at<uint8_t>(0,0);
    nubef->width = Ultima.cols;
    nubef->height = Ultima.rows;
    nubef->resize(nubef->width*nubef->height);
    for(int i = 0; i < Ultima.rows; i++)
      {
      for(int j = 0; j < Ultima.cols; j++)
        {
       cv::Vec3b& bgr = RGB.at<cv::Vec3b>(i,j);
	   cv::Vec3b& na = Mask.at<cv::Vec3b>(i,j);
       pcl::PointXYZRGB p;
       p.r = bgr[2];
       p.g = bgr[1];
       p.b = bgr[0];
       p.x=j;
       p.y=i;
       int dep = Depth2.at<uint16_t>(i,j);
       p.z= dep/100;
       if((dep/100) > 44 && (dep/100) < 462 && p.y >290){
	   //Hist[dep/100] +=1;
		//float distancia = ((0.00170869*p.x+0.435266*p.y-236.199)/0.9003)-dep;
		//cout << distancia << endl;
       if(min > p.z) min = p.z;
	   if(max < p.z) max =p.z;
       nube->push_back(p);}
       nubef->at(j,i) = p;
	   /*else if (p.y > 320){
        float M = -0.0528487*p.x-0.282845*p.x- 193.149;
		M = M/-0.957709 ;
		p.z =M;
		nube -> push_back(p);
		}*/
	   //nube->at(j,i)=p;//}
       /*int distancia = 0.15228*p.z+0.0539963*p.x-0.986861*p.y;
       cv::Vec3b blck = (distancia,distancia,distancia);
       Ultima.at<cv::Vec3b>(i,j) = blck;*/
      }
    }
  if (nube->isOrganized()){
  cout << nube->height << " " << nube->width << endl;
  cout << "Bucle Acabado1 " << nube->size() << endl;
  cout << " Min: "<< min << " Max: " << max <<endl;}
  /*pcl::PassThrough<pcl::PointXYZRGB> pass;
  pass.setInputCloud (nube);
  pass.setFilterFieldName ("z");
  //pass.setKeepOrganized(true);
  pass.setFilterLimits (30.0, 150.0);
  //pass.setFilterLimitsNegative (true);
  pass.filter (*nubef);
  pass.setInputCloud (nubef);
  pass.setFilterFieldName ("y");
  //pass.setKeepOrganized(true);
  pass.setFilterLimits ( 200.0, 600.0);
  //pass.setFilterLimitsNegative (true);
  pass.filter (*nubef2);*/
  nube2 = Region(nube,dis,dis2,7);
  cout << "Bucle Acabado2 " << nube2->size() << endl;
  /*pcl::SampleConsensusModelPlane<pcl::PointXYZRGB>::Ptr dit (new pcl::SampleConsensusModelPlane<pcl::PointXYZRGB> (nube));
  Eigen::Vector4f coefficients = Eigen::Vector4f(0.00170869,0.435266,0.9003,-236.199);
  std::vector<int> inliers;
  dit -> selectWithinDistance (coefficients, dis, inliers);
  pcl::copyPointCloud<pcl::PointXYZRGB>(*nube, inliers, *nube2); */
  cout << "Bucle Acabado3 " << nube2->size() << endl;
  //for (int i =0;i < 640 ; i++) cout <<i << " : " << Hist[i] << ";"<<endl;
 	 //Vis(nube);
	cv::Vec3b blck = (0,0,0);
	if (nube2->size() > 0){
	  for (int pit = 0; pit != nube2->size(); ++pit){
        nubef->at(nube2->at(pit).x,nube2->at(pit).y).x =  bad_point;
        nubef->at(nube2->at(pit).x,nube2->at(pit).y).y =  bad_point;
        nubef->at(nube2->at(pit).x,nube2->at(pit).y).z =  bad_point;
//.........这里部分代码省略.........
开发者ID:pazagra,项目名称:NORM_PCL,代码行数:101,代码来源:pcl_visualizer_demov2.0.cpp

示例10: Match

bool ObjPatchMatcher::Match(const Mat& cimg, const Mat& dmap_raw, Mat& mask_map) {

	/*
	 * precompute feature maps
	 */
	// gradient
	Mat gray_img, gray_img_float, edge_map;
	cvtColor(cimg, gray_img, CV_BGR2GRAY);
	gray_img.convertTo(gray_img_float, CV_32F, 1.f/255);
	Canny(gray_img, edge_map, 10, 50);
	cv::imshow("edge", edge_map);
	cv::imshow("color", cimg);
	cv::waitKey(10);

	Mat grad_x, grad_y, grad_mag;
	Sobel(gray_img_float, grad_x, CV_32F, 1, 0);
	Sobel(gray_img_float, grad_y, CV_32F, 0, 1);
	magnitude(grad_x, grad_y, grad_mag);

	// depth
	Mat dmap_float, pts3d, normal_map;
	if( use_depth ) {
		Feature3D feat3d;
		dmap_raw.convertTo(dmap_float, CV_32F);
		Mat cmp_mask;
		compare(dmap_float, 800, cmp_mask, CMP_LT);
		dmap_float.setTo(800, cmp_mask);
		compare(dmap_float, 7000, cmp_mask, CMP_GT);
		dmap_float.setTo(7000, cmp_mask);
		dmap_float = (dmap_float-800)/(7000-800);

		feat3d.ComputeKinect3DMap(dmap_float, pts3d, false);
		feat3d.ComputeNormalMap(pts3d, normal_map);
	}

	/*
	 *	start searching
	 */
	// init searcher
	//searcher.Build(patch_data, BruteForce_L2);	// opencv bfmatcher has size limit: maximum 2^31
	LSHCoder lsh_coder;
	if(use_code) {
		lsh_coder.Load();
	}
	
	Mat score_map = Mat::zeros(edge_map.rows, edge_map.cols, CV_32F);
	Mat mask_vote_map = Mat::zeros(cimg.rows, cimg.cols, CV_32F);
	mask_map = Mat::zeros(cimg.rows, cimg.cols, CV_32F);
	Mat mask_count = Mat::zeros(cimg.rows, cimg.cols, CV_32S);	// number of mask overlapped on each pixel
	Mat feat;
	int topK = 40;
	int total_cnt = countNonZero(edge_map);
	vector<VisualObject> query_patches;
	query_patches.reserve(total_cnt);

	cout<<"Start match..."<<endl;
	
	float max_dist = 0;
	int cnt = 0;
	char str[30];
	double start_t = getTickCount();
//#pragma omp parallel for
	for(int r=patch_size.height/2; r<gray_img.rows-patch_size.height/2; r+=3) {
		for(int c=patch_size.width/2; c<gray_img.cols-patch_size.width/2; c+=3) {

			/*int rand_r = rand()%gray_img.rows;
			int rand_c = rand()%gray_img.cols;
			if(rand_r < patch_size.height/2 || rand_r > gray_img.rows-patch_size.height/2 ||
				rand_c < patch_size.width/2 || rand_c > gray_img.cols-patch_size.width/2) continue;*/
			int rand_r = r, rand_c = c;

			if(edge_map.at<uchar>(rand_r, rand_c) > 0) 
			{
				cnt++;
				destroyAllWindows();

				Rect box(rand_c-patch_size.width/2, rand_r-patch_size.height/2, patch_size.width, patch_size.height);
				MatFeatureSet featset;
				gray_img_float(box).copyTo(featset["gray"]);
				//grad_mag(box).copyTo(featset["gradient"]);
				if(use_depth)
				{ 
					normal_map(box).copyTo(featset["normal"]);
					dmap_float(box).copyTo(featset["depth"]);
				}
				ComputePatchFeat(featset, feat);
				vector<DMatch> matches;
				if(use_code) 
				{
					BinaryCodes codes;
					HashKey key_val;
					lsh_coder.ComputeCodes(feat, codes);
					HashingTools<HashKeyType>::CodesToKey(codes, key_val);
					MatchCode(key_val, topK, matches);
				}
				else
				{
					MatchPatch(feat, topK, matches);
				}
				
//.........这里部分代码省略.........
开发者ID:flyfj,项目名称:Saliency,代码行数:101,代码来源:ObjPatchMatcher.cpp

示例11: process

 Mat process()
 {
     watershed(image, watershed_markers);
     watershed_markers.convertTo(watershed_markers,CV_8U);
     return watershed_markers;
 }
开发者ID:pmukherj,项目名称:vision_tests,代码行数:6,代码来源:watershed_test.cpp

示例12: main


//.........这里部分代码省略.........
    const string ceresFilename = outputDir + "/ceres_report_" + chName + ".txt";
    ofstream ceresStream(ceresFilename, ios::out);
    if (!ceresStream) {
      throw VrCamException("file open failed: " + ceresFilename);
    }
    ceresStream << summary.FullReport();
    ceresStream << paramsStreamX.str() << "\n" << paramsStreamY.str();
    ceresStream.close();

    if (FLAGS_save_debug_images) {
      LOG(INFO) << "Creating surface fit for channel " << ch << "...";

      BezierCurve<float, double> bezierX(paramsX);
      BezierCurve<float, double> bezierY(paramsY);

      Mat surfaceFit = Mat::zeros(FLAGS_image_height, FLAGS_image_width, CV_32FC1);
      for (int x = 0; x < FLAGS_image_width; ++x) {
        const float vx = bezierX(float(x) / float(maxDimension));
        for (int y = 0; y < FLAGS_image_height; ++y) {
          const float vy = bezierY(float(y) / float(maxDimension));
          surfaceFit.at<float>(Point(x, y)) = vx * vy;
        }
      }

      double minVal;
      double maxVal;
      Point maxLoc;
      Point minLoc;
      minMaxLoc(surfaceFit, &minVal, &maxVal, &minLoc, &maxLoc);
      LOG(INFO) << "surfaceFit min: " << minVal << ", at " << minLoc;
      LOG(INFO) << "surfaceFit max: " << maxVal << ", at " << maxLoc;

      Mat surfacePlot = 255.0f * surfaceFit / maxVal;
      surfacePlot.convertTo(surfacePlot, CV_8UC1);

      // Plot parameters
      static const Point kTextLoc = Point(0, 50);
      static const Scalar kColor = 0;
      putTextShift(surfacePlot, paramsStreamX.str(), kTextLoc, kColor);
      putTextShift(surfacePlot, paramsStreamY.str(), kTextLoc * 2, kColor);

      // Plot image center and surface minima location
      putCircleAndText(surfacePlot, minLoc, kColor);
      Point imageCenter = Point(FLAGS_image_width / 2, FLAGS_image_height / 2);
      putCircleAndText(surfacePlot, imageCenter, kColor);

      Mat surfacePlotJet;
      applyColorMap(surfacePlot, surfacePlotJet, COLORMAP_JET);
      const string surfaceFitPlotFilename =
        outputDir + "/curveFit_fit_" + chName + "_stretched.png";
      imwriteExceptionOnFail(surfaceFitPlotFilename, surfacePlotJet);
    }
  }

  if (FLAGS_test_image_path == "") {
    return EXIT_SUCCESS;
  }

  Mat rawTest = imreadExceptionOnFail(
    FLAGS_test_image_path, CV_LOAD_IMAGE_GRAYSCALE | CV_LOAD_IMAGE_ANYDEPTH);
  const uint8_t rawDepth = rawTest.type() & CV_MAT_DEPTH_MASK;
  if (rawDepth == CV_8U) {
    rawTest = convert8bitTo16bit(rawTest);
  } else if (rawDepth != CV_16U) {
    throw VrCamException("Test image is not 8-bit or 16-bit");
  }
开发者ID:facebook,项目名称:Surround360,代码行数:67,代码来源:TestVignettingCalibration.cpp

示例13: findTransformECC

double cv::findTransformECC(InputArray templateImage,
                            InputArray inputImage,
                            InputOutputArray warpMatrix,
                            int motionType,
                            TermCriteria criteria)
{


    Mat src = templateImage.getMat();//template iamge
    Mat dst = inputImage.getMat(); //input image (to be warped)
    Mat map = warpMatrix.getMat(); //warp (transformation)

    CV_Assert(!src.empty());
    CV_Assert(!dst.empty());


    if( ! (src.type()==dst.type()))
        CV_Error( CV_StsUnmatchedFormats, "Both input images must have the same data type" );

    //accept only 1-channel images
    if( src.type() != CV_8UC1 && src.type()!= CV_32FC1)
        CV_Error( CV_StsUnsupportedFormat, "Images must have 8uC1 or 32fC1 type");

    if( map.type() != CV_32FC1)
        CV_Error( CV_StsUnsupportedFormat, "warpMatrix must be single-channel floating-point matrix");

    CV_Assert (map.cols == 3);
    CV_Assert (map.rows == 2 || map.rows ==3);

    CV_Assert (motionType == MOTION_AFFINE || motionType == MOTION_HOMOGRAPHY ||
        motionType == MOTION_EUCLIDEAN || motionType == MOTION_TRANSLATION);

    if (motionType == MOTION_HOMOGRAPHY){
        CV_Assert (map.rows ==3);
    }

    CV_Assert (criteria.type & TermCriteria::COUNT || criteria.type & TermCriteria::EPS);
    const int    numberOfIterations = (criteria.type & TermCriteria::COUNT) ? criteria.maxCount : 200;
    const double termination_eps    = (criteria.type & TermCriteria::EPS)   ? criteria.epsilon  :  -1;

    int paramTemp = 6;//default: affine
    switch (motionType){
      case MOTION_TRANSLATION:
          paramTemp = 2;
          break;
      case MOTION_EUCLIDEAN:
          paramTemp = 3;
          break;
      case MOTION_HOMOGRAPHY:
          paramTemp = 8;
          break;
    }


    const int numberOfParameters = paramTemp;

    const int ws = src.cols;
    const int hs = src.rows;
    const int wd = dst.cols;
    const int hd = dst.rows;

    Mat Xcoord = Mat(1, ws, CV_32F);
    Mat Ycoord = Mat(hs, 1, CV_32F);
    Mat Xgrid = Mat(hs, ws, CV_32F);
    Mat Ygrid = Mat(hs, ws, CV_32F);

    float* XcoPtr = Xcoord.ptr<float>(0);
    float* YcoPtr = Ycoord.ptr<float>(0);
    int j;
    for (j=0; j<ws; j++)
        XcoPtr[j] = (float) j;
    for (j=0; j<hs; j++)
        YcoPtr[j] = (float) j;

    repeat(Xcoord, hs, 1, Xgrid);
    repeat(Ycoord, 1, ws, Ygrid);

    Xcoord.release();
    Ycoord.release();

    Mat templateZM    = Mat(hs, ws, CV_32F);// to store the (smoothed)zero-mean version of template
    Mat templateFloat = Mat(hs, ws, CV_32F);// to store the (smoothed) template
    Mat imageFloat    = Mat(hd, wd, CV_32F);// to store the (smoothed) input image
    Mat imageWarped   = Mat(hs, ws, CV_32F);// to store the warped zero-mean input image
    Mat allOnes		= Mat::ones(hd, wd, CV_8U); //to use it for mask warping
    Mat imageMask		= Mat(hs, ws, CV_8U); //to store the final mask

    //gaussian filtering is optional
    src.convertTo(templateFloat, templateFloat.type());
    GaussianBlur(templateFloat, templateFloat, Size(5, 5), 0, 0);//is in-place filtering slower?

    dst.convertTo(imageFloat, imageFloat.type());
    GaussianBlur(imageFloat, imageFloat, Size(5, 5), 0, 0);

    // needed matrices for gradients and warped gradients
    Mat gradientX = Mat::zeros(hd, wd, CV_32FC1);
    Mat gradientY = Mat::zeros(hd, wd, CV_32FC1);
    Mat gradientXWarped = Mat(hs, ws, CV_32FC1);
    Mat gradientYWarped = Mat(hs, ws, CV_32FC1);

//.........这里部分代码省略.........
开发者ID:Linyes,项目名称:opencv,代码行数:101,代码来源:ecc.cpp

示例14: allFilled

bool allFilled(const Mat &mat){
	Mat tmp = (mat != 0);
	tmp.convertTo(tmp, CV_64FC1, 1.0 / 255.0);
	return sum(tmp)[0] == (tmp.cols * tmp.rows);
}
开发者ID:FunnyNAYO,项目名称:WaterColorImg,代码行数:5,代码来源:Source.cpp

示例15: GeneWeight

Mat PreGraph::GeneWeight(const vector<float> &feaSpL, const vector<float> &feaSpA, const vector<float> &feaSpB, const Mat &superpixels, const vector<int> &bd, const Mat &adj)
{
	Mat weightMat(Size(spNum, spNum), CV_32F, Scalar(-1));
	int dist = 0;
	float minv = (float)numeric_limits<float>::max();
	float maxv = (float)numeric_limits<float>::min();
	for (int i = 0; i < spNum; ++i)
	{
		for (int j = 0; j < spNum; ++j)
		{
			if (adj.at<ushort>(i, j) == 1)
			{
				dist = sqrt(pow(feaSpL[i] - feaSpL[j], 2)) + sqrt(pow(feaSpA[i] - feaSpA[j], 2)) + sqrt(pow(feaSpB[i] - feaSpB[j], 2));
				weightMat.at<float>(i, j) = dist;
				if (dist < minv)
					minv = dist;
				if (dist > maxv)
					maxv = dist;

				for (int k = 0; k < spNum; ++k)
				{
					if (adj.at<ushort>(j, k) == 1)
					{
						dist = sqrt(pow(feaSpL[k] - feaSpL[i], 2)) + sqrt(pow(feaSpA[k] - feaSpA[i], 2)) + sqrt(pow(feaSpB[k] - feaSpB[i], 2));
						weightMat.at<float>(i, k) = dist;
						if (dist < minv)
							minv = dist;
						if (dist > maxv)
							maxv = dist;
					}

				}
			}

		}
	}

	for (int i = 0; i < bd.size(); ++i)
	{
		for (int j = 0; j < bd.size(); ++j)
		{
			dist = sqrt(pow(feaSpL[bd[i]] - feaSpL[bd[j]], 2)) + sqrt(pow(feaSpA[bd[i]] - feaSpA[bd[j]], 2)) + sqrt(pow(feaSpB[bd[i]] - feaSpB[bd[j]], 2));
			weightMat.at<float>(bd[i], bd[j]) = dist;
			if (dist < minv)
				minv = dist;
			if (dist > maxv)
				maxv = dist;
		}
	}

	for (int i = 0; i < spNum; ++i)
	{
		for (int j = 0; j < spNum; ++j)
		{
			if (weightMat.at<float>(i, j)>-1)
			{
				weightMat.at<float>(i, j) = (weightMat.at<float>(i, j) - minv) / (maxv - minv);
				weightMat.at<float>(i, j) = exp(-weightMat.at<float>(i, j) / theta);
			}
			else
				weightMat.at<float>(i, j) = 0;
		}
	}

	Mat tmpsuperpixels;
	normalize(weightMat, tmpsuperpixels, 255.0, 0.0, NORM_MINMAX);
	tmpsuperpixels.convertTo(tmpsuperpixels, CV_8UC3, 1.0);
	imshow("sp", tmpsuperpixels);
	waitKey();
	return weightMat;
}
开发者ID:GYZHikari,项目名称:Opencv-Saliency,代码行数:71,代码来源:PreGraph.cpp


注:本文中的Mat::convertTo方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。