如何在opencv检测圈后执行一些shell脚本

时间:2012-07-21 09:20:51

标签: c++ shell ubuntu opencv codeblocks

如何在opencv检测圈之后执行一些shell脚本(例如1.sh)?

我已经使用了exec,它可以正常工作,但是在检测到圆圈后opencv程序关闭了,我想要的是程序没有关闭,直到我按“q”键。

这是我的代码:

#include<cv.h>
#include<highgui.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

int main( int argc, char **argv )
{
    CvCapture *capture = 0;
    IplImage  *img = 0;
    int       key = 0;
    CvFont font;

    cvInitFont(&font, CV_FONT_HERSHEY_PLAIN,1.0,1.0,0,1,CV_AA);
    capture = cvCaptureFromCAM( 0 );

    if ( !capture ) {
        fprintf( stderr, "Cannot open initialize webcam!\n" );
        return 1;
    }

    cvNamedWindow( "result", CV_WINDOW_AUTOSIZE );

    img = cvQueryFrame( capture );
    if (!img)
        exit(1);

    IplImage* gray = cvCreateImage( cvGetSize(img), 8, 1 );
    CvMemStorage* storage = cvCreateMemStorage(0);

    while( key != 'q' ) {
        img = cvQueryFrame( capture );
        if( !img ) break;

        cvCvtColor( img, gray, CV_BGR2GRAY );
        cvSmooth( gray, gray, CV_GAUSSIAN, 5, 5 );
        CvSeq* circles = cvHoughCircles( gray, storage, CV_HOUGH_GRADIENT, 2, >gray->height/40, 200, 100/*, 20, 100*/ );
        int i;
        for( i = 0; i < circles->total; i++ )
        {
            float* p = (float*)cvGetSeqElem( circles, i );

            cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), >CV_RGB(50,255,30), 5, 8, 0 );
            cvPutText(img, "CIRCLE",cvPoint(cvRound(p[0]+45),cvRound(p[1]+45)), &font, >CV_RGB(50,10,255));

            if ( circles ) {
                execl("./1.sh", (char *)0);
            }

        }

        cvShowImage( "result", img );
        cvShowImage("gray", gray);
        key = cvWaitKey( 1 );

    }

    //    cvReleaseMemStorage(storage);
    //    cvReleaseImage(gray);
    cvDestroyAllWindows();
    cvDestroyWindow( "result" );
    cvReleaseCapture( &capture );

    return 0;
}

我在ubuntu上使用了代码块。

1 个答案:

答案 0 :(得分:1)

在exec *之后,将不会到达任何代码(在该过程中)。你可以fork,exec,如果你想让程序继续而不等待脚本完成,否则添加一个等待。或者,您可以使用system或popen。

示例:

示例函数来分叉命令并等待:

#include <unistd.h>
/*as a macro*/
#define FORK_EXEC_WAIT(a) ({int s,p;if((p=fork())==0) \
{execvp(a[0],a);}else{while(wait(&s)!= p);}})
/*as a function*/
void fork_exec_wait(char** a) {
    int s,p;
    if((p=fork())==0){
        execvp(a[0],a);
    }else{
        while(wait(&s)!= p);
    }
}

分叉命令并继续

#include <unistd.h>
/*as a macro*/
#define FORK_EXEC(a)    ({if((fork())==0) execvp(a[0],a);})
/*as a function*/
void fork_exec(char** a) {
    int s,p;
    if((p=fork())==0)
        execvp(a[0],a);
}

系统命令是~ship-exec-wait of“sh -c command args”

#include <stdlib.h>
system("command args");

popen命令在没有sh -c的情况下类似,并且会将输出作为流(想想管道,fifo等)

#include <stdio.h>
FILE *fp;
fp = popen("command args", "r");
...
pclose(fp);