int main(int argc, char* argv[]) { // initialize PvAPI if(PvInitialize() == ePvErrSuccess) { //IMPORTANT. Initialize camera structure. See tPvFrame in PvApi.h for more info. memset(&GCamera,0,sizeof(tCamera)); // the only command line argument accepted is the IP@ of the camera to be open if(argc>1) { unsigned long IP = inet_addr(argv[1]); if(IP) { // open the camera if(CameraOpen(IP)) { ListAttributes(); // unsetup the camera CameraClose(); } else printf("Failed to open the camera (maybe not found?)\n"); } else printf("a valid IP address must be entered\n"); } else { // wait for a camera to be plugged WaitForCamera(); if(CameraGrab()) { // open the camera if(CameraOpen()) { ListAttributes(); // unsetup the camera CameraClose(); } else printf("failed to open the camera\n"); } else printf("failed to grab a camera!\n"); } // uninitialize the API PvUnInitialize(); } else printf("failed to initialize the API\n"); return 0; }
void Y_camera_obj(int argc) { tCamera *camera = (tCamera *) ypush_obj(&camera_yObj, sizeof(tCamera)); // memset(handle,0,sizeof(tCamera)); try { // initialise the Prosilica API if (!PvInitialize()) { // wait for a camera to be plugged waitForCamera(); // get a camera from the list cameraGet(camera); // setup the camera cameraSetup(camera); } else { throw "failed to initialise the API\n"; } } catch ( string msg ) { y_error(msg.c_str()); } catch ( char const * msg ) { y_error(msg); } }
int main(int argc, char* argv[]) { // initialise the Prosilica API if(!PvInitialize()) { memset(&GCamera,0,sizeof(tCamera)); // the only command line argument accepted is the IP@ of the camera to be open if(argc>1) { unsigned long IP = inet_addr(argv[1]); if(IP) { // open the camera if(CameraOpen(IP)) { ListAttributes(); // unsetup the camera CameraClose(); } else printf("Failed to open the camera (maybe not found?)\n"); } else printf("a valid IP address must be entered\n"); } else { // wait for a camera to be plugged WaitForCamera(); if(CameraGrab()) { // open the camera if(CameraOpen()) { ListAttributes(); // unsetup the camera CameraClose(); } else printf("failed to open the camera\n"); } else printf("failed to grab a camera!\n"); } // uninitialise the API PvUnInitialize(); } else printf("failed to initialise the API\n"); return 0; }
CameraGigE::CameraGigE(const std::string & name) : Base::Component(name) { LOG(LTRACE) << "Hello CameraGigE from dl\n"; if (PvInitialize() == ePvErrResources) { LOG(LERROR) << "Unable to initialize GigE !!! \n"; //return false; } }
//========================================================= // // INITIALIZATION // //========================================================= // // idlPvInitialize // // Initialize the PvAPI module. // // command line arguments // argv[0]: IN/FLAG debug int idlPvInitialize (int argc, char *argv[]) { tPvErr err; debug = *(IDL_INT *) argv[0]; err = PvInitialize(); return idlPvErrCode(err); }
bool OmniCamera::connect(void) { if(isConnected()) return true; tPvCameraInfoEx info[1]; unsigned long frameSize = 0; //PvLinkCallbackRegister(CameraEventCB,ePvLinkAdd,NULL); //PvLinkCallbackRegister(CameraEventCB,ePvLinkRemove,NULL); if(!PvInitialize()) { while(!PvCameraCount()) Sleep(250); unsigned long numCameras = PvCameraListEx(info, 1, NULL, sizeof(tPvCameraInfoEx));; if ((numCameras == 1) && (info[0].PermittedAccess & ePvAccessMaster)) { _camera.UID = info[0].UniqueId; if(!PvCameraOpen(_camera.UID, ePvAccessMaster, &(_camera.handle))) { if(!PvAttrUint32Get(_camera.handle,"TotalBytesPerFrame",&frameSize)) { _camera.frame.ImageBuffer = new char[frameSize]; unsigned long format=0; PvAttrEnumSet(_camera.handle,"PixelFormat","Bayer8"); char text[100]; PvAttrEnumGet(_camera.handle,"PixelFormat",text,sizeof(text),&format); printf("format %d %s\n",format,text); if(_camera.frame.ImageBuffer) { _camera.frame.ImageBufferSize = frameSize; PvAttrUint32Get(_camera.handle,"Width",&_width); PvAttrUint32Get(_camera.handle,"Height",&_height); PvCaptureStart(_camera.handle); PvAttrEnumSet(_camera.handle, "AcquisitionMode", "Continuous"); PvCommandRun(_camera.handle, "AcquisitionStart"); _connected = true; return true; } } } } } _connected = false; return false; }
int main(int argc, char* argv[]) { // initialise the Prosilica API if(!PvInitialize()) { tCamera Camera; memset(&Camera,0,sizeof(tCamera)); // wait for a camera to be plugged WaitForCamera(); // get a camera from the list if(CameraGet(&Camera)) { // setup the camera if(CameraSetup(&Camera)) { // strat streaming from the camera if(CameraStart(&Camera)) { printf("camera is ready now. Press q to quit or s to take a picture\n"); // wait for the user to quit or snap if(WaitForUserToQuitOrSnap()) { // snap now CameraSnap(&Camera); } // stop the streaming CameraStop(&Camera); } else printf("failed to start streaming\n"); // unsetup the camera CameraUnsetup(&Camera); } else printf("failed to setup the camera\n"); } else printf("failed to find a camera\n"); // uninitialise the API PvUnInitialize(); } else printf("failed to initialise the API\n"); return 0; }
int main(int argc, char* argv[]) { tPvErr errCode; // initialize the PvAPI if((errCode = PvInitialize()) != ePvErrSuccess) { printf("PvInitialize err: %u\n", errCode); } else { //IMPORTANT: Initialize camera structure. See tPvFrame in PvApi.h for more info. memset(&GCamera,0,sizeof(tCamera)); //Set function to handle ctrl+C SetConsoleCtrlHandler(CtrlCHandler, TRUE); printf("Press CTRL-C to terminate\n"); // wait for a camera to be plugged in WaitForCamera(); // get first camera found if(CameraGet()) { // open camera if(CameraSetup()) { // start camera streaming if(CameraStart()) { while(GCamera.Abort == false) CameraSnap(); // stop camera streaming CameraStop(); } // close camera CameraUnsetup(); } } // uninitialize PvAPI PvUnInitialize(); } return 0; }
int main(int argc, char* argv[]) { // initialise the Prosilica API if(!PvInitialize()) { memset(&GCamera,0,sizeof(tCamera)); SetConsoleCtrlHandler(&CtrlCHandler, TRUE); // wait for a camera to be plugged WaitForCamera(); // get a camera from the list if(CameraGet()) { // setup the camera if(CameraSetup()) { // strat streaming from the camera if(CameraStart()) { printf("The camera is ready now. \n"); // snap now while(!GCamera.Abort) CameraSnap(); // stop the streaming CameraStop(); } else printf("failed to start streaming\n"); // unsetup the camera CameraUnsetup(); } else printf("failed to setup the camera\n"); } else printf("failed to find a camera\n"); // uninitialise the API PvUnInitialize(); } else printf("failed to initialise the API\n"); return 0; }
void init() { CHECK_ERR( PvInitialize(), "Failed to initialize Prosilica API" ); // Spend up to 1s trying to find a camera. Finding no camera is not // an error; the user may still be able open one by IP address. for (int tries = 0; tries < 5; ++tries) { cameraNum = PvCameraList(cameraList, MAX_CAMERA_LIST, NULL); if (cameraNum) return; usleep(200000); } /// @todo Callbacks for add/remove camera? }
int main(int argc, char* argv[]) { tPvErr errCode; // initialize the PvAPI if((errCode = PvInitialize()) != ePvErrSuccess) printf("PvInitialize err: %u\n", errCode); else { //IMPORTANT: Initialize camera structure. See tPvFrame in PvApi.h for more info. memset(&GCamera,0,sizeof(tCamera)); // set the CTRL-C handler SetConsoleCtrlHandler(&CtrlCHandler, TRUE); printf("Waiting for camera discovery...\n"); // register camera plugged in callback if((errCode = PvLinkCallbackRegister(CameraEventCB,ePvLinkAdd,NULL)) != ePvErrSuccess) printf("PvLinkCallbackRegister err: %u\n", errCode); // register camera unplugged callback if((errCode = PvLinkCallbackRegister(CameraEventCB,ePvLinkRemove,NULL)) != ePvErrSuccess) printf("PvLinkCallbackRegister err: %u\n", errCode); // wait until ctrl+c break printf("Ctrl+C to break.\n"); WaitForEver(); CameraStop(); CameraUnsetup(); // If thread spawned (see HandleCameraPlugged), wait to finish if(GCamera.ThHandle) WaitThread(); if((errCode = PvLinkCallbackUnRegister(CameraEventCB,ePvLinkAdd)) != ePvErrSuccess) printf("PvLinkCallbackUnRegister err: %u\n", errCode); if((errCode = PvLinkCallbackUnRegister(CameraEventCB,ePvLinkRemove)) != ePvErrSuccess) printf("PvLinkCallbackUnRegister err: %u\n", errCode); // uninitialize the API PvUnInitialize(); } return 0; }
int main(int argc, char* argv[]) { tPvErr errCode; // initialize the PvAPI if((errCode = PvInitialize()) != ePvErrSuccess) printf("PvInitialize err: %u\n", errCode); else { //IMPORTANT: Initialize camera structure. See tPvFrame in PvApi.h for more info. memset(&GCamera,0,sizeof(tCamera)); // set the CTRL-C handler SetConsoleCtrlHandler(&CtrlCHandler, TRUE); printf("Waiting for camera discovery...\n"); // register camera plugged in callback if((errCode = PvLinkCallbackRegister(CameraLinkCallback,ePvLinkAdd,NULL)) != ePvErrSuccess) printf("PvLinkCallbackRegister err: %u\n", errCode); // register camera unplugged callback if((errCode = PvLinkCallbackRegister(CameraLinkCallback,ePvLinkRemove,NULL)) != ePvErrSuccess) printf("PvLinkCallbackRegister err: %u\n", errCode); // All camera setup, event setup, streaming, handled in ePvLinkAdd callback // wait until ctrl+c break or failure printf("***Ctrl+C to break***\n"); WaitForEver(); CameraStop(); EventUnsetup(); CameraUnsetup(); if((errCode = PvLinkCallbackUnRegister(CameraLinkCallback,ePvLinkAdd)) != ePvErrSuccess) printf("PvLinkCallbackUnRegister err: %u\n", errCode); if((errCode = PvLinkCallbackUnRegister(CameraLinkCallback,ePvLinkRemove)) != ePvErrSuccess) printf("PvLinkCallbackUnRegister err: %u\n", errCode); // uninitialize the API PvUnInitialize(); } return 0; }
int main(int argc, char* argv[]) { // initialize PvAPI if(PvInitialize() == ePvErrSuccess) { // set the handler for CTRL-C //SetConsoleCtrlHandler(CtrlCHandler, TRUE); // the following call will only return upon CTRL-C ListCameras(); // uninit the API PvUnInitialize(); } else printf("failed to initialize the API\n"); return 0; }
int main(int argc, char* argv[]) { // initialise the Prosilica API if(!PvInitialize()) { // the only command line argument accepted is the IP@ of the camera to be open if(argc>1) { unsigned long IP = inet_addr(argv[1]); if(IP) { tPvHandle Handle; // open the camera if((Handle = CameraOpen(IP)) != NULL) { // seek the best packet size CameraAdjust(Handle); // close the camera CameraClose(Handle); } else printf("Failed to open the camera (maybe not found?)\n"); } else printf("a valid IP address must be entered\n"); } else printf("usage : AdjustPacket <IP@>\n"); // uninitialise the API PvUnInitialize(); } else printf("failed to initialise the API\n"); return 0; }
//-------------------------------------------------------------------- void ofxVideoGrabberPvAPI::listDevices(){ // lazy initialization of the Prosilica API if( !bPvApiInitiated ){ int ret = PvInitialize(); if( ret == ePvErrSuccess ) { ofLog(OF_LOG_VERBOSE, "PvAPI initialized"); } else { ofLog(OF_LOG_ERROR, "unable to initialize PvAPI"); return; } bPvApiInitiated = true; } ofLog(OF_LOG_NOTICE, "-------------------------------------"); // get a camera from the list tPvUint32 count, connected; tPvCameraInfo list[maxConcurrentCams]; count = PvCameraList( list, maxConcurrentCams, &connected ); if( connected > maxConcurrentCams ) { ofLog(OF_LOG_NOTICE, "more cameras connected than will be listed"); } if(count >= 1) { ofLog(OF_LOG_NOTICE, "listing available capture devices"); for( int i=0; i<count; ++i) { ofLog(OF_LOG_NOTICE, "got camera %s - %s - id: %i\n", list[i].DisplayName, list[i].SerialString, list[i].UniqueId); } } else { ofLog(OF_LOG_NOTICE, "no cameras found"); } ofLog(OF_LOG_NOTICE, "-------------------------------------"); }
int main(int argc, char* argv[]) { tPvErr errCode; int err = 0; // initialize the PvAPI if((errCode = PvInitialize()) != ePvErrSuccess) { printf("PvInitialize err: %u\n", errCode); } else { int c; unsigned long uid = 0; unsigned long addr = 0; bool bGet = false; bool bSet = false; while ((c = getopt (argc, argv, "u:i:gs:h?")) != -1) { switch(c) { case 'u': { if(optarg) uid = atol(optarg); break; } case 'i': { if(optarg) addr = inet_addr(optarg); break; } case 'g': { bGet = true; break; } case 's': { bSet = true; break; } case '?': case 'h': { ShowUsage(); break; } default: break; } } if(uid || ((addr != INADDR_NONE) && (addr != INADDR_ANY))) { tPvHandle Camera; tPvAccessFlags Flags = (bSet ? ePvAccessMaster : ePvAccessMonitor); if(uid) { // wait a bit to leave some time to the API to detect any camera Sleep(500); // and open the camera errCode = PvCameraOpen(uid,Flags,&Camera); } else errCode = PvCameraOpenByAddr(addr,Flags,&Camera); if(errCode == ePvErrSuccess) { if(bGet) // get value errCode = MemRead(Camera); else if(bSet) // set value errCode = MemWrite(Camera,argv[argc-1]); if(errCode != ePvErrSuccess) fprintf(stderr,"Error: %u\n",errCode); err = 1; // close the camera PvCameraClose(Camera); } else { if(errCode == ePvErrNotFound || errCode == ePvErrUnplugged) fprintf(stderr,"No camera detected.\n"); else if(errCode == ePvErrAccessDenied) fprintf(stderr,"Camera already in use.\n"); else fprintf(stderr,"PvCameraOpen fail: %u\n", errCode); err = 1; } } else { ShowUsage(); err = 1; } PvUnInitialize(); } return err; }
//-------------------------------------------------------------------- bool ofxVideoGrabberPvAPI::initGrabber(int w, int h, bool setUseTexture){ width = w; height = h; tPvErr ret; //PvAPI return codes bUseTexture = setUseTexture; memset( &cameraUID, 0, sizeof(cameraUID) ); memset( &cameraHandle, 0, sizeof(cameraHandle) ); memset( &cameraFrame, 0, sizeof(cameraFrame) ); //---------------------------------- 1 - open the sequence grabber // lazy initialization of the Prosilica API if( !bPvApiInitiated ){ ret = PvInitialize(); if( ret == ePvErrSuccess ) { ofLog(OF_LOG_VERBOSE, "PvAPI initialized"); } else { ofLog(OF_LOG_ERROR, "unable to initialize PvAPI"); return false; } bPvApiInitiated = true; } //---------------------------------- 3 - buffer allocation // Create a buffer big enough to hold the video data, // make sure the pointer is 32-byte aligned. // also the rgb image that people will grab pixels = new unsigned char[width*height]; // check for any cameras plugged in int waitIterations = 0; while( PvCameraCount() < 1 ) { ofSleepMillis(250); waitIterations++; if( waitIterations > 8 ) { ofLog(OF_LOG_ERROR, "error: no camera found"); return false; } } //---------------------------------- 4 - device selection tPvUint32 count, connected; tPvCameraInfo list[maxConcurrentCams]; count = PvCameraList( list, maxConcurrentCams, &connected ); if(count >= 1) { bool bSelectedDevicePresent = false; if(bChooseDevice) { //check if selected device is available for( int i=0; i<count; ++i) { if( deviceID == list[i].UniqueId ) { bSelectedDevicePresent = true; cameraUID = list[i].UniqueId; } } } if( !bSelectedDevicePresent ){ cameraUID = list[0].UniqueId; ofLog(OF_LOG_NOTICE, "cannot find selected camera -> defaulting to first available"); ofLog(OF_LOG_VERBOSE, "there is currently an arbitrary hard limit of %i concurrent cams", maxConcurrentCams); } } else { ofLog(OF_LOG_ERROR, "no cameras available"); return false; } //---------------------------------- 5 - final initialization steps ret = PvCameraOpen( cameraUID, ePvAccessMaster, &cameraHandle ); if( ret == ePvErrSuccess ){ ofLog(OF_LOG_VERBOSE, "camera opened"); } else { if( ret == ePvErrAccessDenied ) { ofLog(OF_LOG_ERROR, "camera access denied, probably already in use"); } ofLog(OF_LOG_ERROR, "failed to open camera"); return false; } unsigned long FrameSize = 0; ret = PvAttrUint32Get( cameraHandle, "TotalBytesPerFrame", &FrameSize ); if( ret == ePvErrSuccess ){ // allocate the buffer for the single frame we need cameraFrame.ImageBuffer = new char[FrameSize]; cameraFrame.ImageBufferSize = FrameSize; ofLog(OF_LOG_VERBOSE, "camera asked for TotalBytesPerFrame"); } else { ofLog(OF_LOG_ERROR, "failed to allocate capture buffer"); return false; } ret = PvCaptureStart(cameraHandle); if( ret == ePvErrSuccess ){ ofLog(OF_LOG_VERBOSE, "camera set to capture mode"); } else { if( ret == ePvErrUnplugged ){ ofLog(OF_LOG_ERROR, "cannot start capture, camera was unplugged"); } ofLog(OF_LOG_ERROR, "cannot set to capture mode"); return false; } ret = PvAttrEnumSet(cameraHandle,"FrameStartTriggerMode","Freerun"); if( ret == ePvErrSuccess ){ ofLog(OF_LOG_VERBOSE, "camera set to continuous mode"); } else { ofLog(OF_LOG_ERROR, "cannot set to continous mode"); return false; } ret = PvCommandRun(cameraHandle,"AcquisitionStart"); if( ret == ePvErrSuccess ){ ofLog(OF_LOG_VERBOSE, "camera continuous acquisition started"); } else { // if that fail, we reset the camera to non capture mode PvCaptureEnd(cameraHandle) ; ofLog(OF_LOG_ERROR, "cannot start continuous acquisition"); return false; } bGrabberInited = true; //loadSettings(); ofLog(OF_LOG_NOTICE,"camera is ready now"); //---------------------------------- 6 - setup texture if needed if (bUseTexture){ // create the texture, set the pixels to black and // upload them to the texture (so at least we see nothing black the callback) tex.allocate(width,height,GL_LUMINANCE); memset(pixels, 0, width*height); tex.loadData(pixels, width, height, GL_LUMINANCE); } // we are done return true; }
void GigE::run() { std::cout<<"GigE run"<<std::endl; bool m = PvInitialize(); std::cout<<"I got here"<<std::endl; };
// Initialize camera input bool CvCaptureCAM_PvAPI::open( int index ) { tPvCameraInfo cameraList[MAX_CAMERAS]; tPvCameraInfo camInfo; tPvIpSettings ipSettings; if (PvInitialize()) { } //return false; Sleep(1000); //close(); int numCameras=PvCameraList(cameraList, MAX_CAMERAS, NULL); if (numCameras <= 0 || index >= numCameras) return false; Camera.UID = cameraList[index].UniqueId; if (!PvCameraInfo(Camera.UID,&camInfo) && !PvCameraIpSettingsGet(Camera.UID,&ipSettings)) { /* struct in_addr addr; addr.s_addr = ipSettings.CurrentIpAddress; printf("Current address:\t%s\n",inet_ntoa(addr)); addr.s_addr = ipSettings.CurrentIpSubnet; printf("Current subnet:\t\t%s\n",inet_ntoa(addr)); addr.s_addr = ipSettings.CurrentIpGateway; printf("Current gateway:\t%s\n",inet_ntoa(addr)); */ } else { fprintf(stderr,"ERROR: could not retrieve camera IP settings.\n"); return false; } if (PvCameraOpen(Camera.UID, ePvAccessMaster, &(Camera.Handle))==ePvErrSuccess) { //Set Pixel Format to BRG24 to follow conventions /*Errcode = PvAttrEnumSet(Camera.Handle, "PixelFormat", "Bgr24"); if (Errcode != ePvErrSuccess) { fprintf(stderr, "PvAPI: couldn't set PixelFormat to Bgr24\n"); return NULL; } */ tPvUint32 frameWidth, frameHeight, frameSize; unsigned long maxSize; char pixelFormat[256]; PvAttrUint32Get(Camera.Handle, "TotalBytesPerFrame", &frameSize); PvAttrUint32Get(Camera.Handle, "Width", &frameWidth); PvAttrUint32Get(Camera.Handle, "Height", &frameHeight); PvAttrEnumGet(Camera.Handle, "PixelFormat", pixelFormat,256,NULL); maxSize = 8228; //PvAttrUint32Get(Camera.Handle,"PacketSize",&maxSize); if (PvCaptureAdjustPacketSize(Camera.Handle,maxSize)!=ePvErrSuccess) return false; if (strcmp(pixelFormat, "Mono8")==0) { grayframe = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_8U, 1); grayframe->widthStep = (int)frameWidth; frame = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_8U, 3); frame->widthStep = (int)frameWidth*3; Camera.Frame.ImageBufferSize = frameSize; Camera.Frame.ImageBuffer = grayframe->imageData; } else if (strcmp(pixelFormat, "Mono16")==0) { grayframe = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_16U, 1); grayframe->widthStep = (int)frameWidth; frame = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_16U, 3); frame->widthStep = (int)frameWidth*3; Camera.Frame.ImageBufferSize = frameSize; Camera.Frame.ImageBuffer = grayframe->imageData; } else if (strcmp(pixelFormat, "Bgr24")==0) { frame = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_8U, 3); frame->widthStep = (int)frameWidth*3; Camera.Frame.ImageBufferSize = frameSize; Camera.Frame.ImageBuffer = frame->imageData; } else return false; // Start the camera PvCaptureStart(Camera.Handle); // Set the camera to capture continuously if(PvAttrEnumSet(Camera.Handle, "AcquisitionMode", "Continuous")!= ePvErrSuccess) { fprintf(stderr,"Could not set Prosilica Acquisition Mode\n"); return false; } if(PvCommandRun(Camera.Handle, "AcquisitionStart")!= ePvErrSuccess) { fprintf(stderr,"Could not start Prosilica acquisition\n"); return false; } if(PvAttrEnumSet(Camera.Handle, "FrameStartTriggerMode", "Freerun")!= ePvErrSuccess) { fprintf(stderr,"Error setting Prosilica trigger to \"Freerun\""); return false; } return true; } fprintf(stderr,"Error cannot open camera\n"); return false; }
// Initialize camera input bool CvCaptureCAM_PvAPI::open( int index ) { tPvCameraInfo cameraInfo[MAX_CAMERAS]; if (PvInitialize()) return false; usleep(250000); //close(); int numCameras = PvCameraList(cameraInfo, MAX_CAMERAS, NULL); if (numCameras <= 0 || index >= numCameras) return false; Camera.UID = cameraInfo[index].UniqueId; if (PvCameraOpen(Camera.UID, ePvAccessMaster, &(Camera.Handle))==ePvErrSuccess) { //Set Pixel Format to BRG24 to follow conventions Errcode = PvAttrEnumSet(Camera.Handle, "PixelFormat", "Bgr24"); if (Errcode != ePvErrSuccess) { fprintf(stderr, "PvAPI: couldn't set PixelFormat to Bgr24\n"); return NULL; } tPvUint32 frameWidth, frameHeight, frameSize; PvAttrUint32Get(Camera.Handle, "TotalBytesPerFrame", &frameSize); PvAttrUint32Get(Camera.Handle, "Width", &frameWidth); PvAttrUint32Get(Camera.Handle, "Height", &frameHeight); // Create an image (24 bits RGB Color image) frame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 3); frame->widthStep = frameWidth*3; Camera.Frame.ImageBufferSize = frameSize; Camera.Frame.ImageBuffer = frame->imageData; // Start the camera PvCaptureStart(Camera.Handle); // Set the camera to capture continuously if(PvAttrEnumSet(Camera.Handle, "AcquisitionMode", "Continuous")!= ePvErrSuccess) { fprintf(stderr,"Could not set Prosilica Acquisition Mode\n"); return false; } if(PvCommandRun(Camera.Handle, "AcquisitionStart")!= ePvErrSuccess) { fprintf(stderr,"Could not start Prosilica acquisition\n"); return false; } if(PvAttrEnumSet(Camera.Handle, "FrameStartTriggerMode", "Freerun")!= ePvErrSuccess) { fprintf(stderr,"Error setting Prosilica trigger to \"Freerun\""); return false; } return true; } return false; }
int main(int argc, char* argv[]) { int err = 0; // initialise the Prosilica API if(!PvInitialize()) { int c; unsigned long uid = 0; unsigned long addr = 0; bool bLoad = false; bool bSave = false; while ((c = getopt (argc, argv, "u:i:ls:h?")) != -1) { switch(c) { case 'u': { if(optarg) uid = atol(optarg); break; } case 'i': { if(optarg) addr = inet_addr(optarg); break; } case 'l': { bLoad = true; break; } case 's': { bSave = true; break; } case '?': case 'h': { ShowUsage(); break; } default: break; } } if((uid || addr) && (bSave || bLoad)) { tPvHandle Camera; tPvAccessFlags Flags = (bLoad ? ePvAccessMaster : ePvAccessMonitor); tPvErr Err; bool Done = false; if(uid) { // wait a bit to leave some time to the API to detect any camera Sleep(500); // and open the camera Err = PvCameraOpen(uid,Flags,&Camera); } else Err = PvCameraOpenByAddr(addr,Flags,&Camera); if(!Err) { if(bLoad) // load the camera setup Done = SetupLoad(Camera,argv[argc-1]); else if(bSave) // save the camera setup Done = SetupSave(Camera,argv[argc-1]); if(!Done) fprintf(stderr,"sorry, an error occured\n"); err = 1; // close the camera PvCameraClose(Camera); } else { if(Err == ePvErrNotFound || Err == ePvErrUnplugged) fprintf(stderr,"sorry, couldn't found the camera\n"); else if(Err == ePvErrAccessDenied) fprintf(stderr,"sorry, this camera is already in use\n"); else fprintf(stderr,"sorry, couldn't open the camera for some reason\n"); err = 1; } } else { ShowUsage(); err = 1; } // uninitialise the API PvUnInitialize(); } else { err = 1; fprintf(stderr,"failed to initialise the API\n"); } return err; }
int Process(int argc, const char* argv[]) { std::cout << "/*************************************/" << std::endl; std::cout << "Input LANE_IMG_RECORD" << std::endl; std::cout << "Input LANE_DETECTOR" << std::endl; std::cout << "Input DATA_RECORD" << std::endl; std::cout << "Input SEND_DATA" << std::endl; std::cout << "Input SAMPLING_FREQ" << std::endl; std::cout << "Input COMPRESSION_RATE" << std::endl; std::cout << "Input YAW_ANGLE" << std::endl; std::cout << "Input PITCH_ANGLE" << std::endl; std::cout << "Input TIME_BASELINE" << std::endl; std::cout << "Input LANE_ANALYSER" << std::endl; std::cout << "/*************************************/" << std::endl; if(argc < 11) std::cout << "Not enough parameters" << std::endl; /// Debug Marker int LANE_IMG_RECORD = atoi(argv[1]);//Record the lane image int LANE_DETECTOR = atoi(argv[2]);//Whether detect Lane int DATA_RECORD = atoi(argv[3]);//Record the lane features int SEND_DATA = atoi(argv[4]);//Whether send data int SAMPLING_FREQ = atoi(argv[5]);//Sampling Frequency int COMPRESSION_RATE = atoi(argv[6]);//Compression rate for recording images double YAW_ANGLE = atof(argv[7]);//yaw - X double PITCH_ANGLE = atof(argv[8]);//pitch - Y double TIME_BASELINE = atof(argv[9]);//sec int LANE_ANALYSER = atoi(argv[10]); // std::cout << "LANE_IMG_RECORD: " << LANE_IMG_RECORD << std::endl; // std::cout << "DATA_RECORD: " << DATA_RECORD << std::endl; // std::cout << "SAMPLING_FREQ: " << SAMPLING_FREQ << endl; // std::cout << "COMPRESSION_RATE: " << COMPRESSION_RATE << std::endl; // std::cout << "LANE_DETECTOR: " << LANE_DETECTOR << std::endl; // std::cout << "NUM_WINDOW_SAMPLE: " << NUM_WINDOW_SAMPLE << std::endl; std::cout << "/*****************************************/" << std::endl; std::cout << "Press q / Q / ESC to quit " << std::endl; std::cout << "Press s / S to stop " << std::endl; std::cout << "/*****************************************/" << std::endl; // Init parameters int idx = FRAME_START; //index for image sequence int sampleIdx = 1; //! Get the current time time_t t; time(&t); tm *tmTime = localtime(&t); char currentTime[50]; sprintf(currentTime,"%02d-%02d-%d_%02dh%02dm%02ds",tmTime->tm_mday,tmTime->tm_mon+1,tmTime->tm_year+1900, tmTime->tm_hour,tmTime->tm_min, tmTime->tm_sec); std::cout << "Current Time: " << currentTime << std::endl; //! Init the Record file std::ofstream laneFeatureFile; char *laneFeaturePath = new char[100]; if (DATA_RECORD){ sprintf(laneFeaturePath, FILE_LANE_FEATURES, tmTime->tm_mday,tmTime->tm_mon+1,tmTime->tm_year+1900, tmTime->tm_hour,tmTime->tm_min, tmTime->tm_sec); InitRecordData(laneFeatureFile, laneFeaturePath, laneFeatureName, NUM_LANE_FEATURES); } //! Create a new dir for recording the images char * laneRawImgPath = new char[100]; DIR *pDir = NULL; if(LANE_IMG_RECORD){ do{ sprintf(laneRawImgPath, LANE_PATH_NAME, tmTime->tm_mday,tmTime->tm_mon+1,tmTime->tm_year+1900, tmTime->tm_hour,tmTime->tm_min, tmTime->tm_sec); pDir = opendir(laneRawImgPath); }while (pDir != NULL); mkdir(laneRawImgPath, S_IRWXU); } /* Parameters for Lane Detector */ cv::Mat laneMat; LaneDetector::LaneDetectorConf laneDetectorConf; std::vector<cv::Vec2f> hfLanes; std::vector<cv::Vec2f> lastHfLanes; std::vector<cv::Vec2f> preHfLanes; //lane features std::vector<double> LATSDBaselineVec; std::deque<LaneDetector::InfoCar> lateralOffsetDeque; std::deque<LaneDetector::InfoCar> LANEXDeque; std::deque<LaneDetector::InfoTLC> TLCDeque; LaneDetector::LaneFeature laneFeatures; double lastLateralOffset = 0; double lateralOffset = 0; // Lateral Offset int detectLaneFlag = -1; // init state -> normal state 0 int isChangeLane = 0; // Whether lane change happens int changeDone = 0; // Finish lane change int muWindowSize = 5; // Initial window size: 5 (sample) int sigmaWindowSize = 5; // Initial window size: 5 (sample) // Initialize Lane Kalman Filter cv::KalmanFilter laneKalmanFilter(8, 8, 0); //(rho, theta, delta_rho, delta_theta)x2 cv::Mat laneKalmanMeasureMat(8, 1, CV_32F, cv::Scalar::all(0)); //(rho, theta, delta_rho, delta_theta) int laneKalmanIdx = 0; //Marker of start kalmam LaneDetector::InitlaneFeatures(laneFeatures); if (LANE_DETECTOR) { LaneDetector::InitlaneDetectorConf(laneMat, laneDetectorConf, 1); // KIT 1, ESIEE 2 LaneDetector::InitLaneKalmanFilter(laneKalmanFilter, laneKalmanMeasureMat, laneKalmanIdx); } /* Inter-process communication */ key_t ipckey; int mq_id; struct { long type; char text[1024]; } laneMsg; if (SEND_DATA) { /* Generate the ipc key */ ipckey = ftok(KEY_PATH, 'a'); if(ipckey == -1){ printf("Key Error: %s\n", strerror(errno)); exit(1); } mq_id = msgget(ipckey, 0); if (mq_id == -1) { //MQ doesn't exit mq_id = msgget(ipckey, IPC_CREAT | IPC_EXCL | 0666); printf("LaneDetector creates a new MQ %d\n", mq_id); } else { //MQ does exit mq_id = msgget(ipckey, IPC_EXCL | 0666); printf("LaneDetector uses an existed MQ %d\n", mq_id); } //printf("Lane identifier is %d\n", mq_id); if(mq_id == -1) { throw std::logic_error("Can't build pipeline"); } //printf("This is the LaneDetectSim process, %d\n", getpid()); } /* Entrance of Process */ double initTime = (double)cv::getTickCount(); double intervalTime = 0; double execTime = 0; // Execute Time for Each Frame double pastTime = 0; double lastStartTime = (double)cv::getTickCount(); char key; double delay = 1; //! Camera parameters tCamera Camera; tPvErr errCode; // initialize the PvAPI if((errCode = PvInitialize()) != ePvErrSuccess) { printf("PvInitialize err: %u\n", errCode); } else { //IMPORTANT: Initialize camera structure. See tPvFrame in PvApi.h for more info. memset(&Camera,0,sizeof(tCamera)); // wait for a camera to be plugged in WaitForCamera(); // get first camera found if(CameraGet(&Camera)) { // open camera if(CameraSetup(&Camera)) { // start camera streaming if(CameraStart(&Camera)) { // Start Time in the process while(idx <= FRAME_END) { double startTime = (double)cv::getTickCount(); /* Lane detection starts */ if (WaitForTrigger() && CameraSnap(&Camera)) { /* Read the saved images from the camera */ laneMat = cv::imread(Camera.Filename); // Reduce the size of raw image cv::resize(laneMat, laneMat, cv::Size(WIDTH*COEF, HEIGHT*COEF), CV_INTER_AREA); /* Record the resized raw image */ if (LANE_IMG_RECORD) { std::vector<int> compression_params; compression_params.push_back(CV_IMWRITE_JPEG_QUALITY); compression_params.push_back(COMPRESSION_RATE); char * rawLaneName = new char[50]; char * tempName = new char[100]; sprintf(rawLaneName, LANE_IMG_NAME, idx); strcpy(tempName, laneRawImgPath); strcat(tempName, rawLaneName); cv::imwrite(tempName, laneMat, compression_params); delete tempName; delete rawLaneName; } if (LANE_DETECTOR) { ProcessLaneImage(laneMat, laneDetectorConf, laneKalmanFilter, laneKalmanMeasureMat, laneKalmanIdx, hfLanes, lastHfLanes, lastLateralOffset, lateralOffset, isChangeLane, detectLaneFlag, idx, execTime, preHfLanes, changeDone, YAW_ANGLE, PITCH_ANGLE); } } /* Calculate the running time for every sampling */ pastTime = ((double)cv::getTickCount() - initTime)/cv::getTickFrequency(); // printf("@Lane Sampling passes %f sec\n", pastTime); char *text_pastTime = new char[50]; sprintf(text_pastTime, "LaneDetector Time: %.2f sec", pastTime); cv::putText(laneMat, text_pastTime, cv::Point(0, laneMat.rows-5), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_pastTime; intervalTime = (startTime - lastStartTime)/ cv::getTickFrequency();//get the time between two continuous frames lastStartTime = startTime; /* Generate lane indicators */ if (LANE_DETECTOR && LANE_ANALYSER) { /// First init the baseline, then get lane mass if( pastTime < TIME_BASELINE ){ /// Get lane baseline LaneDetector::GetLaneBaseline(sampleIdx, SAMPLING_TIME, muWindowSize, sigmaWindowSize, lateralOffset, LATSDBaselineVec, lateralOffsetDeque, LANEXDeque, TLCDeque, laneFeatures, intervalTime); //idx_baseline = sampleIdx; } else { //sampleIdx -= idx_baseline; LaneDetector::GenerateLaneIndicators(sampleIdx, SAMPLING_TIME, muWindowSize, sigmaWindowSize, lateralOffset, lateralOffsetDeque, LANEXDeque, TLCDeque, laneFeatures, intervalTime); //! LATSD char *text_LATSD = new char[30]; sprintf(text_LATSD, "L1. LATSD: %.4f", laneFeatures.LATSD); cv::putText(laneMat, text_LATSD, cv::Point(0, 70), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_LATSD; //! LATMEAN char *text_LATMEAN = new char[30]; sprintf(text_LATMEAN, "L2. LATMEAN: %.4f", laneFeatures.LATMEAN); cv::putText(laneMat, text_LATMEAN, cv::Point(0, 80), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_LATMEAN; //! LANEDEV char *text_LANEDEV = new char[30]; sprintf(text_LANEDEV, "L3. LANEDEV: %.4f", laneFeatures.LANEDEV); cv::putText(laneMat, text_LANEDEV, cv::Point(0, 90), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_LANEDEV; //! LANEX char *text_LANEX = new char[30]; sprintf(text_LANEX, "L4. LANEX: %.4f", laneFeatures.LANEX); cv::putText(laneMat, text_LANEX, cv::Point(0, 100), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_LANEX; //! TLC char *text_TLC = new char[30]; sprintf(text_TLC, "L5. TLC: %.4f", laneFeatures.TLC); cv::putText(laneMat, text_TLC, cv::Point(0, 110), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLC; //! TLC_2s char *text_TLC_2s = new char[30]; sprintf(text_TLC_2s, "L6. TLC_2s: %d", laneFeatures.TLC_2s); cv::putText(laneMat, text_TLC_2s, cv::Point(0, 120), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLC_2s; char *text_TLCF_2s = new char[50]; sprintf(text_TLCF_2s, "L7. Fraction_TLC_2s: %f", laneFeatures.TLCF_2s); cv::putText(laneMat, text_TLCF_2s, cv::Point(0, 130), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLCF_2s; //! TLC_halfs char *text_TLC_halfs = new char[30]; sprintf(text_TLC_halfs, "L8. TLC_halfs: %d", laneFeatures.TLC_halfs); cv::putText(laneMat, text_TLC_halfs, cv::Point(0, 140), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLC_halfs; char *text_TLCF_halfs = new char[50]; sprintf(text_TLCF_halfs, "L9. Fraction_TLC_halfs: %f", laneFeatures.TLCF_halfs); cv::putText(laneMat, text_TLCF_halfs, cv::Point(0, 150), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLCF_halfs; //! TLC_min char *text_TLC_min = new char[30]; sprintf(text_TLC_min, "L10. TLC_min: %.4f", laneFeatures.TLC_min); cv::putText(laneMat, text_TLC_min, cv::Point(0, 160), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLC_min; }//end if }//end Generate Lane Indicators /* Record lane features */ if (DATA_RECORD) { laneFeatures.frame = idx; RecordLaneFeatures(laneFeatureFile, laneFeatures, execTime, pastTime); }//end if /* Send the datas as string to fusion center */ if(LANE_DETECTOR & SEND_DATA) { char *str = new char[1024]; memset(str, 0, 1024); CodeMsg(laneFeatures, str); strcpy(laneMsg.text, str);//!!! overflow laneMsg.type = 1; //printf("Data sends: %s\n", laneMsg.text); //! 0 will cause a block/ IPC_NOWAIT will close the app. if(msgsnd(mq_id, &laneMsg, sizeof(laneMsg), 0) == -1) { throw std::runtime_error("LaneDetectSim: msgsnd failed!"); } delete str; } /* Adjust the interval time within fixed frequency */ double execFreq; do { //cv::waitKey(1); execFreq = 1.0 / (((double)cv::getTickCount() - startTime)/cv::getTickFrequency()); }while ( execFreq >= SAMPLING_FREQ ); char *text = new char[30]; sprintf(text, "Process: %.2f Hz", execFreq); cv::putText(laneMat, text, cv::Point(0, 60), cv::FONT_HERSHEY_SIMPLEX, 0.8, CV_RGB(0, 255, 0)); delete text; cv::imshow("Lane", laneMat); key = cv::waitKey(delay); if (key == 'q' || key == 'Q' || 27 == (int)key) //Esc q\Q\key to stop break; else if(key == 's' || key == 'S' ) delay = 0; else delay = 1; sampleIdx++; //update the sampling index idx++; }//end while loop laneFeatureFile.close(); cv::destroyAllWindows(); }//if CameraStart CameraStop(&Camera); }//if CameraSetup CameraUnsetup(&Camera); }//if CameraGet } PvUnInitialize(); return 0; }
// Initialize camera input bool CvCaptureCAM_PvAPI::open( int index ) { tPvCameraInfo cameraList[MAX_CAMERAS]; tPvCameraInfo camInfo; tPvIpSettings ipSettings; if (PvInitialize()) { } //return false; Sleep(1000); //close(); int numCameras=PvCameraList(cameraList, MAX_CAMERAS, NULL); if (numCameras <= 0 || index >= numCameras) return false; Camera.UID = cameraList[index].UniqueId; if (!PvCameraInfo(Camera.UID,&camInfo) && !PvCameraIpSettingsGet(Camera.UID,&ipSettings)) { /* struct in_addr addr; addr.s_addr = ipSettings.CurrentIpAddress; printf("Current address:\t%s\n",inet_ntoa(addr)); addr.s_addr = ipSettings.CurrentIpSubnet; printf("Current subnet:\t\t%s\n",inet_ntoa(addr)); addr.s_addr = ipSettings.CurrentIpGateway; printf("Current gateway:\t%s\n",inet_ntoa(addr)); */ } else { fprintf(stderr,"ERROR: could not retrieve camera IP settings.\n"); return false; } if (PvCameraOpen(Camera.UID, ePvAccessMaster, &(Camera.Handle))==ePvErrSuccess) { tPvUint32 frameWidth, frameHeight; unsigned long maxSize; // By Default, try to set the pixel format to Mono8. This can be changed later // via calls to setProperty. Some colour cameras (i.e. the Manta line) have a default // image mode of Bayer8, which is currently unsupported, so Mono8 is a safe bet for // startup. monocrome = (PvAttrEnumSet(Camera.Handle, "PixelFormat", "Mono8") == ePvErrSuccess); PvAttrUint32Get(Camera.Handle, "Width", &frameWidth); PvAttrUint32Get(Camera.Handle, "Height", &frameHeight); // Determine the maximum packet size supported by the system (ethernet adapter) // and then configure the camera to use this value. If the system's NIC only supports // an MTU of 1500 or lower, this will automatically configure an MTU of 1500. // 8228 is the optimal size described by the API in order to enable jumbo frames maxSize = 8228; //PvAttrUint32Get(Camera.Handle,"PacketSize",&maxSize); if (PvCaptureAdjustPacketSize(Camera.Handle,maxSize)!=ePvErrSuccess) return false; resizeCaptureFrame(frameWidth, frameHeight); return startCapture(); } fprintf(stderr,"Error cannot open camera\n"); return false; }
int main(int argc, char* argv[]) { int err = 0; // initialise PvAPI if(!PvInitialize()) { int c; unsigned long uid = 0; bool bList = false; bool bGet = false; bool bSet = false; bool bMode = false; bool bAddr = false; bool bMask = false; bool bWay = false; char* vMode = NULL; char* vAddr = NULL; char* vMask = NULL; char* vWay = NULL; while ((c = getopt (argc, argv, "lu:gsm:i:n:pw:h?")) != -1) { switch(c) { case 'l': { bList = true; break; } case 'u': { if(optarg) uid = atol(optarg); break; } case 'g': { bGet = true; break; } case 's': { bSet = true; break; } case 'm': { bMode = true; if(optarg) vMode = optarg; break; } case 'i': { bAddr = true; if(optarg) vAddr = optarg; break; } case 'n': { bMask = true; if(optarg) vMask = optarg; break; } case 'w': { bWay = true; if(optarg) vWay = optarg; break; } case '?': case 'h': { ShowUsage(); break; } default: break; } } if(uid || bList) { if(bList) { printf("Searching for cameras ...\n"); Sleep(2000); ListCameras(); } else { printf("Looking for the camera ...\n"); Sleep(1000); if(bGet) { tPvCameraInfo camInfo; tPvIpSettings camConf; struct in_addr addr; if(!PvCameraInfo(uid,&camInfo) && !PvCameraIpSettingsGet(uid,&camConf)) { printf("\t\t\t%s - %s\n",camInfo.SerialString,camInfo.DisplayName); printf("Mode supported:\t\t"); if(camConf.ConfigModeSupport & ePvIpConfigPersistent) printf("FIXED "); if(camConf.ConfigModeSupport & ePvIpConfigDhcp) printf("DHCP "); if(camConf.ConfigModeSupport & ePvIpConfigAutoIp) printf("AutoIP"); printf("\n"); printf("Current mode:\t\t"); if(camConf.ConfigMode & ePvIpConfigPersistent) printf("FIXED\n"); else if(camConf.ConfigMode & ePvIpConfigDhcp) printf("DHCP&AutoIP\n"); else if(camConf.ConfigMode & ePvIpConfigAutoIp) printf("AutoIP\n"); addr.s_addr = camConf.CurrentIpAddress; printf("Current address:\t%s\n",inet_ntoa(addr)); addr.s_addr = camConf.CurrentIpSubnet; printf("Current subnet:\t\t%s\n",inet_ntoa(addr)); addr.s_addr = camConf.CurrentIpGateway; printf("Current gateway:\t%s\n",inet_ntoa(addr)); } else fprintf(stderr,"failed to talk to the camera!\n"); } else if(bSet) { tPvCameraInfo camInfo; tPvIpSettings camConf; bool bApply = false; if(!PvCameraInfo(uid,&camInfo) && !PvCameraIpSettingsGet(uid,&camConf)) { if(bMode && vMode) { unsigned long Mode = 0; if(!strcasecmp(vMode,"fixed")) Mode = ePvIpConfigPersistent; else if(!strcasecmp(vMode,"dhcp")) Mode = ePvIpConfigDhcp; else if(!strcasecmp(vMode,"autoip")) Mode = ePvIpConfigAutoIp; else { fprintf(stderr,"%s isn't a valid mode\n",vMode); err = 1; } if(Mode) { if(camConf.ConfigModeSupport & Mode) { camConf.ConfigMode = (tPvIpConfig)Mode; bApply = true; } else { fprintf(stderr,"%s isn't supported by the camera\n",vMode); err = 1; } } } if(bAddr && vAddr) { camConf.PersistentIpAddr = inet_addr(vAddr); bApply = true; } if(bMask && vMask) { camConf.PersistentIpSubnet = inet_addr(vMask); bApply = true; } if(bWay && vWay) { camConf.PersistentIpGateway = inet_addr(vWay); bApply = true; } if(bApply) { if(PvCameraIpSettingsChange(uid,&camConf)) { fprintf(stderr,"failed to set the configuration!\n"); err = 1; } else printf("Settings changed for %s - %s\n",camInfo.SerialString,camInfo.DisplayName); } } else fprintf(stderr,"failed to talk to the camera!\n"); } else { ShowUsage(); err = 1; } } } else { ShowUsage(); err = 1; } // uninitialise the API PvUnInitialize(); } else { err = 1; fprintf(stderr,"failed to initialise the API\n"); } return err; }