OpenCV: Как отобразить захват веб-камеры в приложении Windows Form? - PullRequest
6 голосов
/ 19 мая 2010

Как правило, мы отображаем движение веб-камеры или видео в окнах opencv с:

      CvCapture* capture = cvCreateCameraCapture(0);
            cvNamedWindow( "title", CV_WINDOW_AUTOSIZE );
   cvMoveWindow("title",x,y);
   while(1) 
   {
    frame = cvQueryFrame( capture );
    if( !frame )
    {
     break;
    }
    cvShowImage( "title", frame );
    char c = cvWaitKey(33);
    if( c == 27 )
    {
     break;
    }
   }

Я попытался использовать PictureBox, который успешно отображать изображение в форме Windows с этим:

 pictureBox1->Image = gcnew System::Drawing::Bitmap( image->width,image->height,image->widthStep,System::Drawing::Imaging::PixelFormat::Undefined, ( System::IntPtr ) image-> imageData);

но когда я пытаюсь отобразить захваченное изображение из видео, оно не работает, вот источник:

            CvCapture* capture = cvCreateCameraCapture(0);
   while(1) 
   {
    frame = cvQueryFrame( capture );
    if( !frame )
    {
     break;
    }
    pictureBox1->Image = gcnew System::Drawing::Bitmap( frame->width,frame->height,frame->widthStep,System::Drawing::Imaging::PixelFormat::Undefined, ( System::IntPtr ) frame-> imageData);
    char c = cvWaitKey(33);
    if( c == 27 )
    {
     break;
    }
   }

Есть ли в любом случае использовать форму Windows вместо OpenCV Windows, чтобы показать видео или веб-камеру?

или что-то не так с моим кодом? спасибо за вашу помощь ..:)

Ответы [ 4 ]

1 голос
/ 18 декабря 2011

Формат пикселей должен быть известен при захвате изображений с камеры, скорее всего, это формат 24-битного BGR. System::Drawing::Imaging::PixelFormat::Format24bppRgb будет самым близким форматом, но вы можете получить странный цветной дисплей. Перестановка цветового компонента решит эту проблему.

На самом деле, здесь доступна .net версия библиотеки opencv: http://code.google.com/p/opencvdotnet/ и здесь: http://www.emgu.com/wiki/index.php/Main_Page

Надеюсь, это поможет!

1 голос
/ 24 декабря 2011

Я не знаю, понравится ли вам это, но вы могли бы использовать OpenGL для показа видеопотока в других окнах, отличных от тех, которые поставляются с opencv. (Захватите рамку и отобразите ее в прямоугольнике ... или что-то в этом роде).

1 голос
/ 23 мая 2010

Совет: используйте VideoInput вместо CvCapture (CvCapture является частью highgui библиотеки, которая предназначена не для производственного использования, а только для быстрого тестирования). Да, домашняя страница VideoInput выглядит странно, но библиотека того стоит.

Вот краткий пример использования VideoInput (извлечен из файла VideoInput.h):

//create a videoInput object
videoInput VI;

//Prints out a list of available devices and returns num of devices found
int numDevices = VI.listDevices();  

int device1 = 0;  //this could be any deviceID that shows up in listDevices
int device2 = 1;  //this could be any deviceID that shows up in listDevices

//if you want to capture at a different frame rate (default is 30) 
//specify it here, you are not guaranteed to get this fps though.
//VI.setIdealFramerate(dev, 60);    

//setup the first device - there are a number of options:

VI.setupDevice(device1);                          //setup the first device with the default settings
//VI.setupDevice(device1, VI_COMPOSITE);              //or setup device with specific connection type
//VI.setupDevice(device1, 320, 240);                  //or setup device with specified video size
//VI.setupDevice(device1, 320, 240, VI_COMPOSITE);  //or setup device with video size and connection type

//VI.setFormat(device1, VI_NTSC_M);                 //if your card doesn't remember what format it should be
                                                    //call this with the appropriate format listed above
                                                    //NOTE: must be called after setupDevice!

//optionally setup a second (or third, fourth ...) device - same options as above
VI.setupDevice(device2);                          

//As requested width and height can not always be accomodated
//make sure to check the size once the device is setup

int width   = VI.getWidth(device1);
int height  = VI.getHeight(device1);
int size    = VI.getSize(device1);

unsigned char * yourBuffer1 = new unsigned char[size];
unsigned char * yourBuffer2 = new unsigned char[size];

//to get the data from the device first check if the data is new
if(VI.isFrameNew(device1)){
    VI.getPixels(device1, yourBuffer1, false, false);   //fills pixels as a BGR (for openCV) unsigned char array - no flipping
    VI.getPixels(device1, yourBuffer2, true, true);     //fills pixels as a RGB (for openGL) unsigned char array - flipping!
}

//same applies to device2 etc

//to get a settings dialog for the device
VI.showSettingsWindow(device1);


//Shut down devices properly
VI.stopDevice(device1);
VI.stopDevice(device2);
0 голосов
/ 04 июля 2013

Другой вариант, который вы могли бы рассмотреть, это использовать emgu. Это оболочка .Net для opencv с элементами управления winforms.

...