Пример #1
0
void createHSVTrackbars(String trackbarWindowName, int *h1, int *h2, int *s1,int *s2,int *v1,int *v2){
	//create window for trackbars
    namedWindow(trackbarWindowName,0);

	//create trackbars and insert them into window  
    createTrackbar( "H MIN", trackbarWindowName, h1, 255, on_trackbar );
    createTrackbar( "H MAX", trackbarWindowName, h2, 255, on_trackbar );
    createTrackbar( "S MIN", trackbarWindowName, s1, 255, on_trackbar );
    createTrackbar( "S MAX", trackbarWindowName, s2, 255, on_trackbar );
    createTrackbar( "V MIN", trackbarWindowName, v1, 255, on_trackbar );
    createTrackbar( "V MAX", trackbarWindowName, v2, 255, on_trackbar );

}
Пример #2
0
int main( int argc, const char** argv ) {
    /*------------- initialization ------------*/
    String sourceName;
    Vec3i spherCoord (0, 0, 0);
    Point3d camPos;
    Vec3i affineTrans (0, 0, 1);
    Mat rotMat = Mat_<double>(3, 3);
    const char* keyMap;
    /*-----------------------------------------*/

    Vec<void*, 4> data (&spherCoord, &camPos, &rotMat, &affineTrans);

    //Standard image that will be used if dont exist arguments
    keyMap = "{1       |   |../Bilder/prep-for-grilling.jpg }";

    //Reading the Callingarguments
    CommandLineParser parser(argc, argv, keyMap);
    sourceName = parser.get<String>("1");

    //Creating the images and testing if it is empty or not
    SOURCE_IMAGE = imread(sourceName);
    if(SOURCE_IMAGE.empty()) {
        printf("Cannot read the image %s\n", sourceName.c_str());
        return -1;
    }

    fillVariables(rotMat);

    //Creating the original image window
    namedWindow("Original Image", 0);
    imshow("Original Image", SOURCE_IMAGE);
    //Creating the affine transformation window
    namedWindow("Affine Transformation");
    //Creating the camera window
    namedWindow("Camera Image");

    //Adding the trackbars for the spherical coordinates
    createTrackbar("radius", "Camera Image", &(spherCoord.val[0]), ALPHA * 15, onTrackbarCam, &data);
    createTrackbar("theta ", "Camera Image", &(spherCoord.val[1]), 90, onTrackbarRotMat, &data);
    createTrackbar("rho   ", "Camera Image", &(spherCoord.val[2]), 360, onTrackbarRotMat, &data);
    //Adding the trackbars for the affine transformation
    createTrackbar("alpha", "Affine Transformation", &(affineTrans.val[0]), 360, onTrackbarAff, &data);
    createTrackbar("beta ", "Affine Transformation", &(affineTrans.val[1]), 360, onTrackbarAff, &data);
    createTrackbar("lamda", "Affine Transformation", &(affineTrans.val[2]), 15, onTrackbarAff, &data);

    waitKey();
    return 0;
}
Пример #3
0
void createTrackbars(){
	namedWindow(trackbarWindowName,0);
	char TrackbarName[50];
	sprintf( TrackbarName, "H_MIN", H_MIN);
	sprintf( TrackbarName, "H_MAX", H_MAX);
	sprintf( TrackbarName, "S_MIN", S_MIN);
	sprintf( TrackbarName, "S_MAX", S_MAX);
	sprintf( TrackbarName, "V_MIN", V_MIN);
	sprintf( TrackbarName, "V_MAX", V_MAX);
	createTrackbar( "H_MIN", trackbarWindowName, &H_MIN, H_MAX, on_trackbar );
	createTrackbar( "H_MAX", trackbarWindowName, &H_MAX, H_MAX, on_trackbar );
	createTrackbar( "S_MIN", trackbarWindowName, &S_MIN, S_MAX, on_trackbar );
	createTrackbar( "S_MAX", trackbarWindowName, &S_MAX, S_MAX, on_trackbar );
	createTrackbar( "V_MIN", trackbarWindowName, &V_MIN, V_MAX, on_trackbar );
	createTrackbar( "V_MAX", trackbarWindowName, &V_MAX, V_MAX, on_trackbar );
}
Пример #4
0
void Calibration::calibrationVisionColor(){
	namedWindow("input");
	namedWindow("values");

	createTrackbar("HMin", "values", &staticVisionColorHelper[0], 180, callbackHueMin, &staticVisionColorHelper[0]);
	createTrackbar("HMax", "values", &staticVisionColorHelper[3], 180, callbackHueMax, &staticVisionColorHelper[3]);

	createTrackbar("SMin", "values", &staticVisionColorHelper[1], 255, callbackSaturationMin, &staticVisionColorHelper[1]);
	createTrackbar("SMax", "values", &staticVisionColorHelper[4], 255, callbackSaturationMax, &staticVisionColorHelper[4]);

	createTrackbar("VMin", "values", &staticVisionColorHelper[2], 255, callbackValueMin, &staticVisionColorHelper[2]);
	createTrackbar("VMax", "values", &staticVisionColorHelper[5], 255, callbackValueMax, &staticVisionColorHelper[5]);

	while(true){
		if(!device){
			inputImage = imread(imagePath);
		}else{
			cam >> inputImage;
		}
		
		applyFilters();
		setMouseCallback("input", callbackMouseClickColor, 0);
	
		draw();
		imshow("input", inputImage);
		medianBlur(outputImage, outputImage, 3);
		imshow("output", outputImage);


		char key = waitKey(10); 
		if(key == 27){
			break;
		}else if(key == 32){
			for(int i = 0 ; i < 3 ; i++){
				staticVisionColor.min.rgb[i] = staticVisionColorHelper[i];
				staticVisionColor.max.rgb[i] = staticVisionColorHelper[i+3];
			}

			handleHSV(staticVisionColor.min);
			handleHSV(staticVisionColor.max);

			saveHSV();
			saveRGB();
			break;
		}
	}
}
Пример #5
0
void RApplication::go()
{	
	CV_Assert(capture.open(Pubvar::videoPath));	
	videoLen = (int)capture.get(CV_CAP_PROP_FRAME_COUNT);	
	fps = (int)capture.get(CV_CAP_PROP_FPS);			
	bDtr = new BDetector(fps, Pubvar::sensitive);	
	fidOI = new bool[videoLen];
	for(int i=0; i<videoLen;++i)
		fidOI[i] = false;

	cout<<"[a]: rewind"<<endl<<"[d]: forward"<<endl<<"[p]: pause / continue"<<endl<<"[o]: object detection"<<endl;

	for (fid=0; fid < videoLen; ++fid)
	{
		sec = fid/fps;
		capture >> frame;		
		processing();
		isSkip = false;

#ifdef DEMO
		imshow(Pubvar::videoPath, frame);			
		createTrackbar( "time", Pubvar::videoPath, &sec, videoLen/fps ,fidControler, (void*)this);				
		
		if(!keyboardCtrl( waitKey(playSpeed) ))
			break;

#elif defined EXPERIMENT			
		if(fid %(videoLen/10) ==0)
		{
			system("cls");
			cout<<Pubvar::videoPath <<" :"<< ((double)fid/videoLen) * 100<<" %"<<endl;			
		}				
#endif
	}

#ifdef EXPERIMENT
	this->writeVideo();	
#endif
}
void ColorImageProcessor::init()
{
	processedImage = new ProcessedImage();
	HMin = 0;
	HMax = 255;
	SMin = 0;
	SMax = 255;
	VMin = 0;
	VMax = 255;
	namedWindow("Settings");
	createTrackbar("HMin", "Settings", &HMin, HMax);
	createTrackbar("HMax", "Settings", &HMax, 255);
	createTrackbar("SMin", "Settings", &SMin, SMax);
	createTrackbar("SMax", "Settings", &SMax, 255);
	createTrackbar("VMin", "Settings", &VMin, VMax);
	createTrackbar("VMax", "Settings", &VMax, 255);
}
void guiAlphaBlend(const Mat& src1, const Mat& src2)
{
	Mat s1,s2;
	if(src1.channels()==1)cvtColor(src1,s1,CV_GRAY2BGR);
	else s1 = src1;
	if(src2.channels()==1)cvtColor(src2,s2,CV_GRAY2BGR);
	else s2 = src2;
	namedWindow("alphaBlend");
	int a = 0;
	createTrackbar("a","alphaBlend",&a,100);
	int key = 0;
	Mat show;
	while(key!='q')
	{
		addWeighted(s1,1.0-a/100.0,s2,a/100.0,0.0,show);
		imshow("alphaBlend",show);
		key = waitKey(1);
		if(key=='f')
		{
			a = (a > 0) ? 0 : 100;
			setTrackbarPos("a","alphaBlend",a);
		}
	}
}
/*Ben rotate te imazhit sipas nje kendi qe kontrollohet me ane te nje trackbari (-180 <= kendi <= 180)
  dhe e shfaq kete imazh ne dritaren me emer @param emriDritares
 */
void Editim::rotullo(Mat& imazhOrig, string emriDritares)
{
    int vleraSliderRotate = 180;
    createTrackbar("Rotate", emriDritares, &vleraSliderRotate, 360);
    while (true){
        double kendi = vleraSliderRotate-180; //hiqet 180 per te marre vlera -180 deri 180
        imazhOrig = fotoOrigjinale.clone(); //sigurohet qe rotullimi te aplikohet mbi imazhin origjinal
                                            //perndryshe kemi rrotullime te pafundme
        int gjatesia = max(imazhOrig.cols, imazhOrig.rows); //permasa e imazhit pas rrotullimit
        Point2f pikaBaze(gjatesia/2.0, gjatesia/2.0); //pika sipas te ciles behet rrotullimi (qendra)
        Mat matriceRrotullimi = getRotationMatrix2D(pikaBaze, kendi, 1.0); //llogaritet matrica
                                                                           //me te cilen behet rrotullimi
        //transformohet imazhi sipas kesaj matrice
        warpAffine(imazhOrig, imazhOrig, matriceRrotullimi, Size(gjatesia, gjatesia));
        imshow(emriDritares, imazhOrig);
        int tastIshtypur = waitKey(50);
        if (tastIshtypur == 27)
        {
            cout << "Rrotullimi caktivizohet. " <<endl;
            break;
        }
    }
    return;
}
void createTrackbars(){
    //create window for trackbars
    namedWindow(trackbarWindowName,0);
    //create memory to store trackbar name on window
    char TrackbarName[50];
    sprintf( TrackbarName, "H_MIN", H_MIN);
    sprintf( TrackbarName, "H_MAX", H_MAX);
    sprintf( TrackbarName, "S_MIN", S_MIN);
    sprintf( TrackbarName, "S_MAX", S_MAX);
    sprintf( TrackbarName, "V_MIN", V_MIN);
    sprintf( TrackbarName, "V_MAX", V_MAX);
    //create trackbars and insert them into window
    //3 parameters are: the address of the variable that is changing when the trackbar is moved(eg.H_LOW),
    //the max value the trackbar can move (eg. H_HIGH),
    //and the function that is called whenever the trackbar is moved(eg. on_trackbar)
    //                                  ---->    ---->     ---->
    createTrackbar( "H_MIN", trackbarWindowName, &H_MIN, H_MAX, on_trackbar );
    createTrackbar( "H_MAX", trackbarWindowName, &H_MAX, H_MAX, on_trackbar );
    createTrackbar( "S_MIN", trackbarWindowName, &S_MIN, S_MAX, on_trackbar );
    createTrackbar( "S_MAX", trackbarWindowName, &S_MAX, S_MAX, on_trackbar );
    createTrackbar( "V_MIN", trackbarWindowName, &V_MIN, V_MAX, on_trackbar );
    createTrackbar( "V_MAX", trackbarWindowName, &V_MAX, V_MAX, on_trackbar );
}
bool OpenCVItemProcessing::Startup()
{
	namedWindow(windowName, WINDOW_AUTOSIZE);
	namedWindow("Debug", WINDOW_AUTOSIZE);
	camera.set(CV_CAP_PROP_AUTO_EXPOSURE, 0);
	

	createTrackbar("Exposure", "Debug", &exposure, 12,
		[](int value, void* userdata)
		{

		},
		&ref0
		);

	createTrackbar("r_max", "Debug", &r_max, 255,
		[](int value, void* userdata)
		{

		},
		&ref0
	);

	createTrackbar("r_min", "Debug", &r_min, 255,
		[](int value, void* userdata)
		{

		},
		&ref0
		);

	createTrackbar("g_max", "Debug", &g_max, 255,
		[](int value, void* userdata)
		{

		},
		&ref0
		);

	createTrackbar("g_min", "Debug", &g_min, 255,
		[](int value, void* userdata)
		{

		},
		&ref0
		);

	createTrackbar("b_max", "Debug", &b_max, 255,
		[](int value, void* userdata)
		{

		},
		&ref0
		);

	createTrackbar("b_min", "Debug", &b_min, 255,
		[](int value, void* userdata)
		{

		},
		&ref0
		);


	return true;
}
Пример #11
0
void guiZoom(InputArray src, OutputArray dst)
{
	const int width = src.size().width;
	const int height = src.size().height;

	string wname = "Zoom";
	namedWindow(wname);
	int th=1;
	//Point mpt = Point(width/2, height/2);
	Point mpt = Point(410, 230);
	int d = 40; 
	int z = 7;

	createTrackbar("x", wname,&mpt.x, width-1);
	createTrackbar("y", wname,&mpt.y, height-1);
	createTrackbar("d", wname,&d, min(width,height)-1);
	createTrackbar("zoom", wname,&z, 20);
	int key = 0;

	setMouseCallback(wname,onMouse,&mpt);
	
	Mat dest;
	Mat input = src.getMat();

	int mode = 0;
	while(key!='q')
	{
		input.copyTo(dest);
		z = max(z,1);

		Rect rct = Rect(mpt.x, mpt.y, d,d);
		Scalar color = Scalar(0,0,255);
		int thick = 2;

		rectangle(dest, rct, color, thick);

		Mat crop;
		dest(rct).copyTo(crop);
		Mat res;
		resize(crop,res, Size(z*d,z*d), 0,0, INTER_NEAREST);
		
		if(res.cols <= dest.cols && res.rows <= dest.rows)
		{
			if(mode==0) res.copyTo(dest(Rect(0, 0 ,res.size().width, res.size().height)));
			else if(mode==1) res.copyTo(dest(Rect(dest.cols-1-res.size().width, 0, res.size().width, res.size().height)));
			else if(mode==2) res.copyTo(dest(Rect(dest.cols-1-res.size().width, dest.rows-1-res.size().height, res.size().width, res.size().height)));
			else if(mode==3) res.copyTo(dest(Rect(0, dest.rows-1-res.size().height, res.size().width, res.size().height)));
		}

		imshow(wname,dest);
		key = waitKey(1);

		setTrackbarPos("x",wname,mpt.x);
		setTrackbarPos("y",wname,mpt.y);
		if(key=='r')
		{
			mode++;
			if(mode>4) mode=0;
		}
		if(key=='s')
		{
			imwrite("out.png", dest);
		}
	}

	dest.copyTo(dst);
	destroyWindow(wname);
}
Пример #12
0
//Thread d'initialisation
void *drawingAndParam(void * arg)
{
	string winParametrage = "Thresholded";
	string winDetected = "Parametrages";
	char key;
	drawing = false;
	onDrawing = true;
	pthread_mutex_init(&mutexVideo, NULL);
#if output_video == ov_remote_ffmpeg
	int errorcode = avformat_open_input(&pFormatCtx, "tcp://192.168.1.1:5555", NULL, NULL);
	if (errorcode < 0) {
		cout << "ERREUR CAMERA DRONE!!!" << errorcode;
		return 0;
	}
	avformat_find_stream_info(pFormatCtx, NULL);
	av_dump_format(pFormatCtx, 0, "tcp://192.168.1.1:5555", 0);
	pCodecCtx = pFormatCtx->streams[0]->codec;
	AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
	if (pCodec == NULL) {
		cout << "ERREUR avcodec_find_decoder!!!";
		return 0;
	}
	if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
		cout << "ERREUR avcodec_open2!!!";
		return 0;
	}
	//pFrame = av_frame_alloc();
	//pFrameBGR = av_frame_alloc();
	pFrame = avcodec_alloc_frame();
	pFrameBGR = avcodec_alloc_frame();
	bufferBGR = (uint8_t*)av_mallocz(avpicture_get_size(PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height) * sizeof(uint8_t));
	avpicture_fill((AVPicture*)pFrameBGR, bufferBGR, PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height);
	pConvertCtx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_BGR24, SWS_SPLINE, NULL, NULL, NULL);
	img = cvCreateImage(cvSize(pCodecCtx->width, (pCodecCtx->height == 368) ? 360 : pCodecCtx->height), IPL_DEPTH_8U, 3);
	if (!img) {
		cout << "ERREUR PAS D'IMAGE!!!";
		return 0;
	}

	pthread_t ii;
	pthread_create(&ii, NULL, getimg, NULL);

#else	
	VideoCapture cap(0); //capture video webcam

#endif
	HH=179;LS=1;HS=255;LV=1;HV=255;LH=1;
	namedWindow(winDetected, CV_WINDOW_NORMAL);
	Mat frame;
	setMouseCallback(winDetected, MouseCallBack, NULL);
	while(true)
	{	
		if(onDrawing) //Tant que l'utilisateur ne commence pas la sélection!
		{
			#if output_video != ov_remote_ffmpeg
				bool bSuccess = cap.read(frame); // Nouvelle capture
			if (!bSuccess) {
				cout << "Impossible de lire le flux video" << endl;
				break;
			}
			#else
				pthread_mutex_lock(&mutexVideo);
				memcpy(img->imageData, pFrameBGR->data[0], pCodecCtx->width * ((pCodecCtx->height == 368) ? 360 : pCodecCtx->height) * sizeof(uint8_t) * 3);
				pthread_mutex_unlock(&mutexVideo);
				frame = cv::cvarrToMat(img, true);
			#endif
		imshow(winDetected, frame);
		}
		if(!onDrawing && !drawing) //On affiche en direct la sélection de l'utilisateur
		{
			Mat tmpFrame=frame.clone();
			rectangle(tmpFrame, rec, CV_RGB(51,156,204),1,8,0);
			imshow(winDetected, tmpFrame);
		}
		if(drawing) //L'utilisateur a fini de sélectionner
		{
			//cible Ball(1);
			namedWindow(winParametrage, CV_WINDOW_NORMAL);
			setMouseCallback(winDetected, NULL, NULL);	
			rectangle(frame, rec, CV_RGB(51,156,204),2,8,0);
			imshow(winDetected, frame);
			Mat selection = frame(rec);
			Ball.setPicture(selection);
			while(key != 'q')
			{
				//Trackbar pour choix de la couleur
				createTrackbar("LowH", winParametrage, &LH, 179); //Hue (0 - 179)
				createTrackbar("HighH", winParametrage, &HH, 179);
				//Trackbar pour Saturation comparer au blanc
				createTrackbar("LowS", winParametrage, &LS, 255); //Saturation (0 - 255)
				createTrackbar("HighS", winParametrage, &HS, 255);
				//Trackbar pour la lumminosite comparer au noir
				createTrackbar("LowV", winParametrage, &LV, 255);//Value (0 - 255)
				createTrackbar("HighV", winParametrage, &HV, 255);
				Mat imgHSV;

				cvtColor(selection, imgHSV, COLOR_BGR2HSV); //Passe de BGR a HSV

				Mat imgDetection;

				inRange(imgHSV, Scalar(LH, LS, LV), Scalar(HH, HS, HV), imgDetection); //Met en noir les parties non comprises dans l'intervalle de la couleur choisie par l'utilisateur

				//Retire les bruits
				erode(imgDetection, imgDetection, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
				dilate(imgDetection, imgDetection, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

				dilate(imgDetection, imgDetection, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
				erode(imgDetection, imgDetection, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

				imshow(winParametrage, imgDetection);

				//Calcul de la "distance" à la cible. On s'en sert comme seuil.
				Moments position;
				position = moments(imgDetection);
				Ball.lastdZone = position.m00;

				key = waitKey(10);
			}
			
			//Extraction des points d'intérêts de la sélection de l'utilisateur
			Mat graySelect;
			int minHessian = 800;
			cvtColor(selection, graySelect, COLOR_BGR2GRAY);
			Ptr<SURF> detector = SURF::create(minHessian);
			vector<KeyPoint> KP;
			detector->detect(graySelect, KP);
			Mat KPimg;
			drawKeypoints(graySelect, KP, KPimg, Scalar::all(-1), DrawMatchesFlags::DEFAULT);
			Mat desc;
			Ptr<SURF> extractor = SURF::create();
			extractor->compute(graySelect, KP, desc);
			Ball.setimgGray(graySelect);
			Ball.setKP(KP);
			Ball.setDesc(desc);
			break;
		}
		key = waitKey(10);
	}
	//Fin de l'initiatlisation on ferme toutes les fenêtres et on passe au tracking
	destroyAllWindows();
#if output_video != ov_remote_ffmpeg
	cap.release();
#endif
}
Пример #13
0
//-----------------------------------【main( )函数】------------------------------------------------------------------------------  
//      描述:控制台应用程序的入口函数,我们的程序从这里开始  
//--------------------------------------------------------------------------------------------------------------------------------  
int main(int agrc, char** agrv)
{


	initMain();//初始化

	//载入原图  
	g_srcImage = imread(".\\sourcePicture\\3.bmp");

	//添加噪音
	if (noice)
	{
		salt(g_srcImage);
		imwrite("./output/noice.bmp", g_gradBmp);
	}

	//定义一个Mat类型并给其设定ROI区域  
	//g_srcImage = g_srcImage(Rect(0, 0, 250, 250));

	//判断是否读取成功
	if (!g_srcImage.data)
	{
		cout << "读取图片srcImage时出错!\n";
		return false;
	}


	//将原图转换为灰度图  
	cvtColor(g_srcImage, g_srcGrayImage, CV_BGR2GRAY);

	ShowHelpText(g_srcGrayImage);

	//histGram(g_srcGrayImage);
	Edge edge1;
	Edge edge(g_srcGrayImage);//传值初始化
	edge.Init();//深入初始化
	//edge.edgeDection(1,NULL);

	//创建Canny检测的tracebar
	namedWindow("Canny检测");
	//namedWindow("listk1"); namedWindow("listk1&&listk2");
	createTrackbar("参数值:", "Canny检测", &g_cannyLowThreshold, 160, edge.on_Canny);
	namedWindow("g_mergImg");//, CV_WINDOW_NORMAL
	//createTrackbar("梯度:", "g_mergImg", &TH, 80, edge.edgeDection);	
	//createTrackbar("相似度:", "g_mergImg", &TH1, 40, edge.edgeDection);
	//createTrackbar("相似度:", "g_edge[1]", &g_di, 80, edge.listK);
	edge.edgeDection();
	//edge.edgeDection1();
	g_srcGrayImage.convertTo(g_srcGrayImage, CV_32F);

	if (xls)
	{
		edge.outXls(g_srcGrayImage, "./output/gray.xls");
		//outxlsInt(g_biGrad, "./output/bigrad.xls");
	}

	//cout << g_ltedge << endl;
	//将原图转换为灰度图
	//g_dstImage.convertTo(g_dstImage, CV_8UC1);
	//namedWindow("dst");
	//imshow("dst", g_dstImage);
	//显示梯度图片

	g_srcGrad.convertTo(g_gradBmp, CV_8UC1);
	imshow("梯度图", g_gradBmp);
	imwrite("./output/grad.bmp", g_gradBmp);





	//轮询获取按键信息,若按下Q,程序退出  
	while ((char(waitKey(1)) != 'q')) {}
	return 0;
}
Пример #14
0
void skizImage::CreateTrackbar(string trackbar,string window,int *slider,const int sliderMax) 
{
	createTrackbar(trackbar,window,slider,sliderMax,OnTrackbar,this);
    waitKey(0);	
}
int main(int argc, char* argv[]) {
    if ( argc < 1 ) {
        std::cout 2<< "Usage: " << argv[0] << " image_file_name\n";
        return 0;
    }

    // Step 0: Initialize stuff
    cv::Size imagesize = cv::Size(640, 480);
    cv::Mat img = cv::Mat(imageSize, CV_8UC1);
    vector<vector<cv::Point2f> > imagePoints;
    cv::Mat cameraMatrix, distCoeffs;

    cv::Size fieldDimensions = cv::Size();
    std::vector<std::vector<cv::Point3f> > imagePoints;
    std::vector<std::vector<cv::Point3f> > objectPoints;
    // points will correspond to found poi in the image
    std::vector<cv::Point3f > objectPoint();

    char* window = "Image";
    cv::namedWindow(window, CV_WINDOW_AUTOSIZE);

    // Step 1: Load image
    image = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);

    // Step 2: Find green field / Color stuff
    bool found = false;
    // Step 2a: Select part that will be mostly green, tweak
    h_max=0;
    h_min=0;
    s_min=0;
    s_max=0;
    v_min=0;
    v_max=0;
    createTrackbar( "hmin:", window, &h_min, 256, showField );
    createTrackbar( "hmax:", window, &h_max, 256, showField );
    createTrackbar( "smin:", window, &s_min, 256, showField );
    createTrackbar( "smax:", window, &s_max, 256, showField );
    createTrackbar( "vmin:", window, &v_min, 256, showField );
    createTrackbar( "vmax:", window, &v_max, 256, showField );
    /**
    // Step 2b: Filter out non-field parts by masking them
    cv::Mat mask;

    // Step 2c: Detect points of interest (corners etc)
    distCoeffs = cv::Mat::zeros(8, 1, CV_64F);
    std::vector<cv::Point2f > corners;
    int maxCorners = 20;
    double qualityLevel = 0.01;
    double minDistance = 10;

    cv::goodFeaturesToTrack(image, corners, maxCorners, qualityLevel, minDistance,
                            mask, blockSize=3, useHarrisDetector=false, k=0.04 );

    imagePoints.push_back(corners)
    // Step 2d: Draw feedback

    // Step 3: Transform what we think is the field into a rectangle
    if(found)
    {
        // First determine correct ordering of objectpoints (RANSAC?)

        // Add found POI to the stack
        imagePoints.push_back(corners);
        // This'll be fine, as long as we don't edit objectPoint
        objectPoints.push_back(objectPoint);

        rms = cv::calibrateCamera(objectPoints,
                                  imagePoints,
                                  imageSize,
                                  cameraMatrix,
                                  distCoeffs,
                                  rvecs,
                                  tvecs,
                                  CV_CALIB_FIX_K4|CV_CALIB_FIX_K5);

    }
    cout << "Re-projection error reported by calibrateCamera: "<< rms << endl;
    bool calibrated = (cv::checkRange(cameraMatrix) && cv::checkRange(distCoeffs));
    // Done for now.
    **/

    return 0;
}
int main(int argc, char* argv[])
{
	//if we would like to calibrate our filter values, set to true.
	bool calibrationMode = true;

	//Matrix to store each frame of the webcam feed
	Mat cameraFeed;
	Mat threshold;
	Mat HSV;

	if(calibrationMode){
		//create slider bars for HSV filtering
		createTrackbars();
	}
	//video capture object to acquire webcam feed
	VideoCapture capture;
	//open capture object at location zero (default location for webcam)
	capture.open(0);
	//set height and width of capture frame
	capture.set(CV_CAP_PROP_FRAME_WIDTH,FRAME_WIDTH);
	capture.set(CV_CAP_PROP_FRAME_HEIGHT,FRAME_HEIGHT);
	//start an infinite loop where webcam feed is copied to cameraFeed matrix
	//all of our operations will be performed within this loop
	waitKey(1000);
	while(1){
		//store image to matrix
		capture.read(cameraFeed);

		src = cameraFeed;

  		if( !src.data )
  		{ return -1; }

		//convert frame from BGR to HSV colorspace
		cvtColor(cameraFeed,HSV,COLOR_BGR2HSV);

		if(calibrationMode==true){

		//need to find the appropriate color range values
		// calibrationMode must be false

		//if in calibration mode, we track objects based on the HSV slider values.
			cvtColor(cameraFeed,HSV,COLOR_BGR2HSV);
			inRange(HSV,Scalar(H_MIN,S_MIN,V_MIN),Scalar(H_MAX,S_MAX,V_MAX),threshold);
			morphOps(threshold);
			imshow(windowName2,threshold);

		//the folowing for canny edge detec
			/// Create a matrix of the same type and size as src (for dst)
	  		dst.create( src.size(), src.type() );
	  		/// Convert the image to grayscale
	  		cvtColor( src, src_gray, CV_BGR2GRAY );
	  		/// Create a window
	  		namedWindow( window_name, CV_WINDOW_AUTOSIZE );
	  		/// Create a Trackbar for user to enter threshold
	  		createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold);
	  		/// Show the image
			trackFilteredObject(threshold,HSV,cameraFeed);
		}
		else{
			//create some temp fruit objects so that
			//we can use their member functions/information
			Object blue("blue"), yellow("yellow"), red("red"), green("green");

			//first find blue objects
			cvtColor(cameraFeed,HSV,COLOR_BGR2HSV);
			inRange(HSV,blue.getHSVmin(),blue.getHSVmax(),threshold);
			morphOps(threshold);
			trackFilteredObject(blue,threshold,HSV,cameraFeed);
			//then yellows
			cvtColor(cameraFeed,HSV,COLOR_BGR2HSV);
			inRange(HSV,yellow.getHSVmin(),yellow.getHSVmax(),threshold);
			morphOps(threshold);
			trackFilteredObject(yellow,threshold,HSV,cameraFeed);
			//then reds
			cvtColor(cameraFeed,HSV,COLOR_BGR2HSV);
			inRange(HSV,red.getHSVmin(),red.getHSVmax(),threshold);
			morphOps(threshold);
			trackFilteredObject(red,threshold,HSV,cameraFeed);
			//then greens
			cvtColor(cameraFeed,HSV,COLOR_BGR2HSV);
			inRange(HSV,green.getHSVmin(),green.getHSVmax(),threshold);
			morphOps(threshold);
			trackFilteredObject(green,threshold,HSV,cameraFeed);

		}
		//show frames
		//imshow(windowName2,threshold);

		imshow(windowName,cameraFeed);
		//imshow(windowName1,HSV);

		//delay 30ms so that screen can refresh.
		//image will not appear without this waitKey() command
		waitKey(30);
	}
	return 0;
}
Пример #17
0
vector<vector<double>> calibrator(CvCapture* cap){

	// Ball Threshold values
	int h_min, s_min, v_min, h_max, s_max, v_max, write, variablecount,getconfig;

	namedWindow("Thresh");
	namedWindow("Thresitud");
	Mat frame;
	vector<Mat> frames;
	vector<double> ball;
	vector<double> goal;
	vector<double> lines;
	vector<int> *arrptr;
	bool onlyonce = true;
	vector<vector<double>> values;

	string filename = "config.txt";
	string variable;
	string line_from_config;
	ofstream fout;
	ifstream fin;
	vector<string> line;
	variablecount = 1;

	fin.open(filename);

	getconfig = 0;
	write = 0;
	h_min = 0;
    s_min = 0;
    v_min = 0;
	h_max = 255,
	s_max = 255;
	v_max = 255;

	createTrackbar( "H min", "Thresh", &h_min, SLIDER_MAX, NULL);
	createTrackbar( "H max", "Thresh", &h_max, SLIDER_MAX, NULL);
	createTrackbar( "S min", "Thresh", &s_min, SLIDER_MAX, NULL);
	createTrackbar( "S max", "Thresh", &s_max, SLIDER_MAX, NULL);
	createTrackbar( "V min", "Thresh", &v_min, SLIDER_MAX, NULL);
	createTrackbar( "V max", "Thresh", &v_max, SLIDER_MAX, NULL);
	// WRITE to file
	createTrackbar("WRITE", "Thresh", &write, 1, NULL);
	createTrackbar("QUIT CONFIG", "Thresh", &getconfig, 1, NULL);

	cout<< "Enne ifi" << endl;

	if (fin.is_open())
	{
		cout << "IF" << endl;
		getline(fin,line_from_config);
		while (line_from_config != "")
		{
			cout<<"WHILE"<<endl;
			line = split(line_from_config, " ");
			if (line[0] == "Ball"){
				for (int i = 1; i < line.size(); i++){
					ball.push_back(atoi(line[i].c_str()));
					cout<<line[i]<<endl;
				}
			}

			else if (line[0] == "Goal"){
				for (int i = 1; i < line.size(); i++){
					goal.push_back(atoi(line[i].c_str()));
					cout<<line[i]<<endl;
				}
			}

			else if (line[0] == "Lines"){
				for (int i = 1; i < line.size(); i++){
					lines.push_back(atoi(line[i].c_str()));
					cout<<line[i]<<endl;
				}
			}
			else
			{
				break;
			}



			getline(fin,line_from_config);
		}
		values.push_back(ball);
		values.push_back(goal);
		values.push_back(lines);

	}
	else
	{
		cout<<"File is empty or not opened"<<endl;
	}

	while (true){

	if (write == 1)	{

		if (onlyonce)
		{
			fout.open(filename);
			values.clear();
			onlyonce = false;
		}


		if(variablecount == 1){
			variable = "Ball";
			ball.push_back(h_min);
			ball.push_back(s_min);
			ball.push_back(v_min);
			ball.push_back(h_max);
			ball.push_back(s_max);
			ball.push_back(v_max);
			values.push_back(ball);

		}
		else if(variablecount == 2){
			variable = "Goal";
			goal.push_back(h_min);
			goal.push_back(s_min);
			goal.push_back(v_min);
			goal.push_back(h_max);
			goal.push_back(s_max);
			goal.push_back(v_max);
			values.push_back(goal);

		}
		else if(variablecount == 3){
			variable = "Lines";
			lines.push_back(h_min);
			lines.push_back(s_min);
			lines.push_back(v_min);
			lines.push_back(h_max);
			lines.push_back(s_max);
			lines.push_back(v_max);
			values.push_back(lines);
		}


		fout << variable << " " << h_min << " " << s_min <<
			" " << v_min << " "  << h_max << " " << s_max <<
			" " << v_max << endl;

		cout <<  variable << " " << h_min << " " << s_min <<
			" " << v_min << " "  << h_max << " " << s_max <<
			" " << v_max << endl;

		variablecount = variablecount +1;

		h_min = 0;
		s_min = 0;
		v_min = 0;
		h_max = 255,
		s_max = 255;
		v_max = 255;
		write = 0;


		setTrackbarPos("H min", "Thresh", h_min);
		setTrackbarPos("S min", "Thresh", s_min);
		setTrackbarPos("V min", "Thresh", v_min);
		setTrackbarPos("H max", "Thresh", h_max);
		setTrackbarPos("S max", "Thresh", s_max);
		setTrackbarPos("V max", "Thresh", v_max);
		setTrackbarPos("WRITE", "Thresh", write);
	}

	if (getconfig == 1)
	{

	}


	// take a frame, threshold it, display the thresholded image
	frame = cvQueryFrame( cap );
	frames = thresholder(frame,h_min, s_min, v_min, h_max, s_max, v_max ); // added values as argument, previously h_min, s_min ....

	imshow("Thresh", frames[0]);
	imshow("CALIBRATOR", frames[0]);



	int c = cvWaitKey(10);
	if( (char)c == 27) {
    cvDestroyAllWindows();
    return values;
	}

	}

}
Пример #18
0
	int getPegthresholdFromUser(IplImage *img, Gui *gui, string message, int pegThreshVal, Rect r, cv::Mat &fgMaskPeg)
	{
		cv::Mat element[1];
		int count = 0;

		element[0] = getStructuringElement(MORPH_ELLIPSE, Size(8, 8), Point(0, 0));
		
		window_name = gui->windowName();
		cvDestroyWindow(window_name.c_str());
		cvNamedWindow(window_name.c_str(), CV_WINDOW_AUTOSIZE);
		cvMoveWindow(window_name.c_str(), 100, 100);

		img0 = (IplImage *)cvClone(img);
		char TrackbarName[50];
		sprintf(TrackbarName, "thresh x %d", slider_max);

		slider_val = pegThreshVal;
		createTrackbar(TrackbarName, window_name, &slider_val, slider_max, 0);

		

		Mat src, im1, im3;
		src = Mat(img0);

		im1 = Mat::zeros(src.size(), src.type());
		cvtColor(src, im3, CV_BGR2HSV);
		vector<vector<Point> > pegsI;
		while (1)
		{
			pegsI.clear();
			Mat channel[3];
			split(im3, channel);


			//Mat fgMaskRing;
			inRange(channel[2], slider_val, 255, fgMaskPeg);
			// ROI
			for (int y = 0; y < fgMaskPeg.rows; y++)
			{
				for (int x = 0; x < fgMaskPeg.cols; x++)
				{
					if (!(x >= r.tl().x && x <= r.br().x && y >= r.tl().y && y <= r.br().y))
					{
						fgMaskPeg.at<uchar>(Point(x, y)) = 0;
					}
				}
			}
			erode(fgMaskPeg, fgMaskPeg, element[0]);
			dilate(fgMaskPeg, fgMaskPeg, element[0]);
			erode(fgMaskPeg, fgMaskPeg, element[0]);
			dilate(fgMaskPeg, fgMaskPeg, element[0]);

			//p.copyTo(p, fgMaskPeg);
			for (int y = 0; y < src.rows; y++)
			{
				for (int x = 0; x < src.cols; x++)
				{
					if (fgMaskPeg.at<uchar>(Point(x, y)))
					{
						im1.at<Vec3b>(Point(x, y)) = src.at<Vec3b>(Point(x, y));
					}
					else
					{
						im1.at<Vec3b>(Point(x, y)) = Vec3b(0,0,0);
					}
				}
			}

			Mat mask = fgMaskPeg.clone();
			vector<Vec4i> hierarchy_ring;

			//imshow("Initial mask", initial_ring_mask);
			findContours(mask, pegsI, hierarchy_ring, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
			count = pegsI.size();



			cout << "count Pegs->" << count << endl;
			cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, 8);
			putText(im1, message.c_str(), cvPoint(0, 60), CV_FONT_HERSHEY_SIMPLEX, .7, Scalar(255, 255, 0), 1);

			imshow(window_name.c_str(), im1);
			char key = cvWaitKey(40);
			if ((key == '\r' || key == '\n' || key == '\r\n'))
			{
				if (count == 12)
				{
					break;
				}
			}
			count = 0;
		} 
		cvReleaseImage(&img0);
		return slider_val;
	}
Mat IITkgp_functions::binarization(Mat image, int type)
{
/**
 * @param type
 * type = 1 for adaptive;
 * type = 2 for Otsu
 * type = 3 for Normal Threshold by GUI
**/

    // Convert the image to Gray

    Mat gray,binary;
    threshold_type = 0;

    cvtColor(image, gray, CV_BGR2GRAY);

    //adaptive Binarization
    if(type == 1)
    {     
      blockSize = (windowsize * 10) + 1;
      adaptiveThreshold(  gray, binary, maximum_BINARY_value, ADAPTIVE_THRESH_GAUSSIAN_C,  threshold_type,  blockSize, tempwinval);
      //TempBinary.copyTo(binary);

    }

    // Otsu Thresholding
    if(type == 2)
    {
      double val = threshold( gray, binary, 100, maximum_BINARY_value, cv::THRESH_OTSU | cv::THRESH_BINARY);
      printf("threshold value is %lf\n",val);
    }

    //GUI Threshold
    if(type == 3)
    {
      gray.copyTo(TempGray);
      /// Create a window to display results
        namedWindow( "BinaryThresholding", CV_WINDOW_KEEPRATIO );

        createTrackbar( "Value", "BinaryThresholding", & binary_threshold_value, maximum_BINARY_value, BinaryThreshold );

        /// Call the function to initialize
        BinaryThreshold( 0, 0 );
        waitKey(0);
        printf("threshold value is %d\n",binary_threshold_value);
        TempBinary.copyTo(binary);

    }
    
    if(type == 4)
    {
      gray.copyTo(TempGray);
      namedWindow( "AdaptiveBinarization", CV_WINDOW_KEEPRATIO );
      createTrackbar( "WindowSize (10n+1)", "AdaptiveBinarization", & windowsize, 100, AdaptiveBinaryThreshold );
      createTrackbar( "Val", "AdaptiveBinarization", & tempwinval, 100, AdaptiveBinaryThreshold );
      /// Call the function to initialize
      AdaptiveBinaryThreshold( 0, 0 );
      waitKey(0);
      TempBinary.copyTo(binary);

    }

    // Fixed Threshold
    if(type == 5)
    {
      binary_threshold_value = 211;
      threshold( gray, binary,  binary_threshold_value, maximum_BINARY_value,threshold_type );
    }

    return (binary);

}
Пример #20
0
void Tracker::track(int nsamples, double dynamicp)
{
	Mat frame;
	Mat hsvFrame;
	bool finishInnerLoop = false;
	Particles pf(nsamples, dynamicp);
	bool wasInit = false;
  
	namedWindow("fr", CV_WINDOW_KEEPRATIO);
	createTrackbar("kapa", "fr", &(pf.measure_param), 1000, NULL);
	setMouseCallback("fr", wrappedOnMouse, (void*)this);

	do{
		(*capture) >> frame;

		if(!frame.empty()){

			if(wasInit){
				cvtColor(frame, hsvFrame , CV_RGB2HSV);
				pf.resample();
				pf.predict();
				pf.measure(hsvFrame);
				pf.new_state(hsvFrame);

				for(int i=0 ; i<pf.pnum ; i++) {
					circle(frame, Point(pf.particles[i].pos_x, pf.particles[i].pos_y), 5, 
					       Scalar(0,0,255));
					circle(frame, Point((int)pf.mean_pos_x, (int)pf.mean_pos_y), 5, 
						   Scalar(255,0,0), -1);
					// rectangle(frame, Point(pf.particles[i].pos_x + (pf.width>>1), pf.particles[i].pos_y + (pf.height>>1)),
					//           Point(pf.particles[i].pos_x - (pf.width>>1), pf.particles[i].pos_y - (pf.height>>1)),
					//           Scalar(0,255,0));
				}
			}

			imshow("fr", frame);

			finishInnerLoop = false;
			switch(waitKey(2) & 255){
				case 't': // zastaveni prehravani a moznost oznacit objekt mysi

					filling = false;
					filled = false;
						
					while(!finishInnerLoop){
						Mat frameCopy = frame.clone();

						// vykresleni obdelniku, pokud tahnu mysi
						if(filling)
							rectangle(frameCopy, Point(px1, py1), Point(px2, py2), Scalar(255), 2);

						if(filled){
							filling = false;
							filled = false;
						}

						imshow("fr", frameCopy);

						switch(waitKey(2) & 255){
							case 't':
							case ' ':
								finishInnerLoop = true;
								Rect rct(Point(px1,py1), Point(px2,py2));
								if(rct.width <= 0 || rct.height <= 0)
									break;
								cvtColor(frame, hsvFrame , CV_RGB2HSV);
								pf.init_samples(hsvFrame, rct);
								wasInit = true;
								break;
						}
					}
					break;
			}

			writer->write(frame);
		}
	} while( !frame.empty() );
} 
Пример #21
0
Result CalSpermCount::calNum(Mat img)
{
	Mat tmp, tmp_back;
//	int col = 800, row = 600;
	Size dsize = Size(nshowcol, nshowrow);
	Mat image2show = Mat(dsize,CV_8U);

	GaussianBlur(img,img,cv::Size(5,5), 1.5);

	if(nShowMidRst)
	    ShowImage("after filtering", img);
	//cvSmooth(img, img, CV_MEDIAN, 3, 0, 0, 0); //中值滤波,消除小的噪声;

	//Mat element(9,9,CV_8U,Scalar(1));
	Mat element = getStructuringElement(MORPH_RECT,Size(10,10));
	erode(img, tmp,element);
    //ShowImage("erode",tmp);

	dilate(tmp,tmp_back,element);
	::resize(tmp_back, image2show,dsize);
	//cvNamedWindow("dilate");
	//imshow("dilate", image2show);
	//ShowImage("dilate",tmp_back);

	morphologyEx(img,dst_gray,MORPH_TOPHAT,element);
	//morphologyEx(img,dst_gray,MORPH_BLACKHAT,cv::Mat());
	//dst_gray = img;

	//绘制直方图
	Histgram1D hist;
	hist.stretch(dst_gray,0.01f);
	if(nShowMidRst)
	    ShowImage("Histogram", hist.getHistogramImage(dst_gray, 1));
	Mat tmpImage;

	//::equalizeHist(dst_gray,tmpImage);
	//ShowImage("拉伸后", tmpImage);
	//ShowImage("拉伸后Histogram",  hist.getHistogramImage(tmpImage, 1));

    if(nShowMidRst)
   {
		ShowImage("Picture EQ", hist.stretch(dst_gray, 50));
	    ShowImage("after draw, Histogram",  hist.getHistogramImage(hist.stretch(dst_gray,50), 1));
	}

	dst_gray =  hist.stretch(dst_gray, 50);
	//dst_gray =  ::equalizeHist(dst_gray,dst_gray);


	//dst_gray = tmp_back  - img  ;
	//dst_gray = img  ;
	::resize(dst_gray, image2show,dsize);
#if 0 // No GUI
	if(nShowMidRst)
	    cvNamedWindow(WINDOWNAME);

	::createTrackbar("filter pattern",WINDOWNAME,&g_nThresholdType,4,on_Theshold);
	createTrackbar("theshold value",WINDOWNAME,&g_nThresholdValue,255,on_Theshold);
#endif
	//初始化自定义回调函数
	on_Theshold(0,0);

	//adaptiveThreshold(dst_gray,dstimgbw,255,adaptive_method,CV_THRESH_BINARY,blocksize,0);
    //cvAdaptiveThreshold(img, dst_bw,255,adaptive_method,//自适应阀值,blocksize为奇数
    // CV_THRESH_BINARY,blocksize,offset);


//	::resize(dstimgbw, image2show,dsize);
//	cvNamedWindow("src2");
//	imshow("src2", image2show);
//		waitKey(0);

	vector<vector<Point> > contours;

	findContours(dstimgbw,contours,CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

	Mat rst(img.size(),CV_8U,Scalar(0));
	drawContours(rst,contours,-1,255,1);

	int cmin = minArea;
	int cmax = maxArea;
	vector<vector<Point> >::iterator itc = contours.begin();
	int i = 0;
	result.LittleNum = 0;
	result.AimNum = 0;
	result.LargeNum = 0;
	fallcount = contours.size();
	while(itc!=contours.end())
	{

		if(itc->size() < cmin )
		{
			result.LittleNum ++;
			itc = contours.erase(itc);
			//i++;
		}
		else if(itc->size() > cmax)
		{
			itc = contours.erase(itc);
			result.LargeNum ++;
		}
		else
		{
			result.AimNum ++;
		    cout <<i<<" = "<< itc->size()<<endl;
			i++;
			++itc;
		}
	}

	Mat rst2(img.size(),CV_8UC3,Scalar(0,0,0));
	drawContours(rst2,contours,-1,cv::Scalar(255,255,255),1);

	char sz1[MAX_PATH],sz2[MAX_PATH],sz3[MAX_PATH];
	char sz4[MAX_PATH];
	char szError[MAX_PATH] = " ";

	fcount = fratio * result.AimNum;


	if(result.LittleNum/fallcount > fminRatio  || result.LargeNum/fallcount > fmaxRatio)
			sprintf(szError,"Sample is dirty");

	sprintf(sz1,"Aim Num = %d",   result.AimNum);
	sprintf(sz2,"Little Num=%d",  result.LittleNum);
	sprintf(sz3,"Large Num=%d",   result.LargeNum);
	sprintf(sz4,"Count =%3.3f",   fcount);

	putText(rst2,sz1,cv::Point(10,10),cv::FONT_HERSHEY_PLAIN, 1.0,   cv::Scalar(255,0,0),     2);
	putText(rst2,sz2,cv::Point(10,30),cv::FONT_HERSHEY_PLAIN, 1.0,   cv::Scalar(255,0,0),     2);
	putText(rst2,sz3,cv::Point(10,50),cv::FONT_HERSHEY_PLAIN, 1.0,   cv::Scalar(255,0,0),     2);
	putText(rst2,sz4,cv::Point(10,70),cv::FONT_HERSHEY_PLAIN, 1.0,   cv::Scalar(255,0,255),     2);
	putText(rst2,szError,cv::Point(10,90),cv::FONT_HERSHEY_PLAIN, 1.0,   cv::Scalar(0,0,255),     2);

	cout << "Aim Num = "<<result.AimNum<<endl;
	cout << "Little Num = "<<result.LittleNum<<endl;
	cout << "Large Num = "<<result.LargeNum<<endl;
	cout << "Count = "<<fcount<<endl;
	cout << "all = "<<contours.size()<<endl;

	ShowImage("result",rst2);

	//waitKey(0);
	return result;
}
Пример #22
0
void CalibratorWindow::addTrackbarToWindow() {
    this->topLineY1 = 0;
    this->topLineY2 = 0;
    this->bottomLineY1 = maxHeight;
    this->bottomLineY2 = maxHeight;
    this->leftLineX1 = 0;
    this->leftLineX2 = 0;
    this->rightLineX1 = maxWidth;
    this->rightLineX2 = maxWidth;
    this->angleThreshold = 10;
    this->margin = 0;
    this->proturdingThreshold = 0;
    this->featureMinHessian = 800;
    this->keyPointSizeThreshold = 30;

    char * filename = this->getConfigFilename();
    ifstream configFile(filename);
    string line;

    if (configFile.is_open()) {
        getline(configFile, line);
        this->topLineY1 = atoi(line.c_str());

        getline(configFile, line);
        this->topLineY2 = atoi(line.c_str());

        getline(configFile, line);
        this->bottomLineY1 = atoi(line.c_str());

        getline(configFile, line);
        this->bottomLineY2 = atoi(line.c_str());

        getline(configFile, line);
        this->leftLineX1 = atoi(line.c_str());

        getline(configFile, line);
        this->leftLineX2 = atoi(line.c_str());

        getline(configFile, line);
        this->rightLineX1 = atoi(line.c_str());

        getline(configFile, line);
        this->rightLineX2 = atoi(line.c_str());

        getline(configFile, line);
        this->angleThreshold = atoi(line.c_str());

        getline(configFile, line);
        this->margin = atoi(line.c_str());

        getline(configFile, line);
        this->proturdingThreshold = atoi(line.c_str());

        getline(configFile, line);
        this->featureMinHessian = atoi(line.c_str());

        getline(configFile, line);
        this->keyPointSizeThreshold = atoi(line.c_str());

        getline(configFile, line);
        this->keyPointCountThreshold = atoi(line.c_str());

        configFile.close();
    }

    free(filename);

    createTrackbar("TopLine Y1", calibratorWindow, &(this->topLineY1), maxHeight, &onCalibratorChange, this);
    createTrackbar("TopLine Y2", calibratorWindow, &(this->topLineY2), maxHeight, &onCalibratorChange, this);
    createTrackbar("BottomLine Y1", calibratorWindow, &(this->bottomLineY1), maxHeight, &onCalibratorChange, this);
    createTrackbar("BottomLine Y2", calibratorWindow, &(this->bottomLineY2), maxHeight, &onCalibratorChange, this);
    createTrackbar("LeftLine X1", calibratorWindow, &(this->leftLineX1), maxWidth, &onCalibratorChange, this);
    createTrackbar("LeftLine X2", calibratorWindow, &(this->leftLineX2), maxWidth, &onCalibratorChange, this);
    createTrackbar("RightLine X1", calibratorWindow, &(this->rightLineX1), maxWidth, &onCalibratorChange, this);
    createTrackbar("RightLine X2", calibratorWindow, &(this->rightLineX2), maxWidth, &onCalibratorChange, this);
    createTrackbar("Angle Threshold", calibratorWindow, &(this->angleThreshold), 90, &onCalibratorChange, this);
    createTrackbar("Inside Margin", calibratorWindow, &(this->margin), 100, &onCalibratorChange, this);
    createTrackbar("Proturding Threshold", calibratorWindow, &(this->proturdingThreshold), 100, &onCalibratorChange, this);
    createTrackbar("Feature Min Hessian", calibratorWindow, &(this->featureMinHessian), 2000, &onCalibratorChange, this);
    createTrackbar("Key Point Size Threshold", calibratorWindow, &(this->keyPointSizeThreshold), 200, &onCalibratorChange, this);
    createTrackbar("Key Point Count Threshold", calibratorWindow, &(this->keyPointCountThreshold), 200, &onCalibratorChange, this);

}
Пример #23
0
OCV::OCV(const int incamdev, const string hsvFilterConfFile, const int expressiondiv, const bool verb)  throw(ExOCV)
{
  expressionDiv = expressiondiv;
  lastExLevel=0;
  verbose = verb;
  paused = false;
  
  if (readHSVFilterConf(hsvFilterConfFile)!=0) {
    cerr << "WARNING! Not possible to read configuration file with HSV range. Default bounds will be used." << endl;
    hsvRange.lowerb = Scalar(DEF_H_MIN, DEF_S_MIN, DEF_V_MIN);
    hsvRange.upperb = Scalar(DEF_H_MAX, DEF_S_MAX, DEF_V_MAX);
  }
  
  try
  {
    // Initialize structuring elements for morphological operations
    morphERODE  = getStructuringElement( MORPH_RECT, Size(ERODE_RECT_PIXEL,ERODE_RECT_PIXEL));
    morphDILATE = getStructuringElement( MORPH_RECT, Size(DILATE_RECT_PIXEL,DILATE_RECT_PIXEL));
    trackState = TrackStt::NO_TRACK;

    #ifdef VIDEO_IN
      string camdev = "sample/footsample.avi";
      //~ string camdev = "sample.avi";
    #else
      int camdev = incamdev; 
    #endif
    
    // auto exposure control
    if (disable_exposure_auto_priority(camdev) != 0)
      cerr << "WARNING! Not possible to disable auto priority. The delay in the camera reading may be too much!" << endl;
      //~ throw(ExOCV("Not possible to disable auto priority")); 
        
    // open video to write
    #ifdef VIDEO_OUT
      time_t now;
      time(&now);
      string voname = "vsample"+to_string(now)+".avi";
      videoOut.open(voname, 0, 30.0, Size(FRAME_WIDTH, FRAME_HEIGHT));
      if (!videoOut.isOpened())
        throw(ExOCV("Not possible to open write video")); 
    #endif
    
    // get image for layout and paused state
    if (get_png(layout6x, LAYOUT_PNG_NAME) || get_png(layoutPaused, PAUSED_PNG_NAME))
      throw(ExOCV("Not possible to read controller layout")); 
    
    //open capture object at location zero (default location for webcam)
    videoCap.open(camdev);
    if (!videoCap.isOpened())
      throw(ExOCV("Not possible to open input device or video")); 
    // TODO implement reading the fps by using v4l2 lib
    int frameIntervalUS = read_frame_interval_us(videoCap);
    if (frameIntervalUS == -1) {
      cerr << "WARNING!  Not possible to read the frame interval from device " << camdev << 
              ". Default value will be used" << endl;
      frameIntervalUS = DEF_FRAME_INT_US;
    }
    cerr << "Frame interval us: " << frameIntervalUS << endl;
    
    debouceFrames = (int)((double)DEBOUNCE_TIME_MS*1000/(double)frameIntervalUS);
    debounceCounter = 0;

    //set height and width of capture frame
    videoCap.set(CV_CAP_PROP_FRAME_WIDTH,FRAME_WIDTH);
    videoCap.set(CV_CAP_PROP_FRAME_HEIGHT,FRAME_HEIGHT);
    
    namedWindow(W_NAME_FEED); moveWindow(W_NAME_FEED, 10, 10);
    // TODO Implement something more oop
    createTrackbar( "+ light -", W_NAME_FEED, &sLowerbTrackebar, 256, NULL);
    //~ cerr << getBuildInformation() << endl;
    #ifdef SHOW_WIN
      namedWindow(W_NAME_HSV); moveWindow(W_NAME_HSV, 800, 10);
      namedWindow(W_NAME_THRESHOLD); moveWindow(W_NAME_THRESHOLD, 400, 10);
    #endif
    }
  catch (const exception &e)
  {
    throw(ExOCV(e.what())); 
  }
}