how to caputre video from usb camera in MJPEG pixel format - c++

i working in stereo cameras project (connect two usb cameras to my laptop) but the proplem is my web cameras format are "YUYV" and this format did't support that to run two cameras togther so how i do that ? that's my code in c++ and opencv3
#include <opencv2/opencv.hpp>
/**
* #file main.cpp
* #brief OpenCV Stereo Webcam.
* #author Martin Peris (http://www.martinperis.com)
* #date 21/08/2011
*/
/*
main.cpp - Implement a simple stereo webcam with OpenCV and C++
Copyright (c) 2011 Martin Peris (http://www.martinperis.com).
All right reserved.
This application is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This application is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this application; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
//This works for me on OpenCV 2.0 with 2 Logicool webcams.
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <vector>
#include <iostream>
#include <sstream>
#include <opencv2/video/background_segm.hpp>
#include <opencv2/video/background_segm.hpp>
#include "cv.h"
#include "highgui.h"
#include <iostream>
//Maybe in OpenCV2.2 the correct include statement would be:
//#include "opencv2/opencv.hpp"
int main(int, char**)
{
cv::VideoCapture capLeft(4); // open the Left camera
cv::VideoCapture capRight(2); // open the Right camera
if(!capLeft.isOpened() || !capRight.isOpened()) // check if we succeeded
{
std::cerr << "ERROR: Could not open cameras." << std::endl;
return -1;
}
capLeft.set(CV_CAP_PROP_FPS, 25);
capRight.set(CV_CAP_PROP_FPS, 25);
// Values taken from output of Version 1 and used to setup the exact same parameters with the exact same values!
capLeft.set(CV_CAP_PROP_FRAME_WIDTH, 320);
capLeft.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
capRight.set(CV_CAP_PROP_FRAME_WIDTH, 320);
capRight.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
cv::namedWindow("Left",1);
cv::namedWindow("Right",1);
for(;;)
{
bool isValid = true;
cv::Mat frameLeft;
cv::Mat frameRight;
try
{
capLeft >> frameLeft; // get a new frame from left camera
capRight >> frameRight; //get a new frame from right camera
}
catch( cv::Exception& e )
{
std::cout << "An exception occurred. Ignoring frame. " << e.err << std::endl;
isValid = false;
}
if (isValid)
{
try
{
cv::imshow("Left", frameLeft);
cv::imshow("Right", frameRight);
/************************************************************
* This is the place for all the cool stuff that you *
* want to do with your stereo images *
************************************************************/
//TODO:...
}
catch( cv::Exception& e )
{
/************************************************************
* Sometimes an "Unrecognized or unsuported array type" *
* exception is received so we handle it to avoid dying *
************************************************************/
std::cout << "An exception occurred. Ignoring frame. " << e.err << std::endl;
}
}
if(cv::waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}

Related

VideoCapture not working C++ windows

So I have played around in OpenCV a bunch before and never run into this problem. I am implementing a MeanShift algorithm and trying to do it on video devices, images, and videos. Devices and images work; however, no matter what I try, when I run VideoCapture on my filename (whether setting it in the Constructor or using the VideoCapture::open() method, and whether local or with a full path) I always get stuck in my error check.
Thoughts? Ideas? code below. running in Visual Studio 2012
#include "opencv2\highgui\highgui.hpp"
#include "opencv2\core\core.hpp"
#include "opencv2\opencv.hpp"
#include "opencv2\video\video.hpp"
#include <string>
using cv::Mat;
using std::string;
enum Filetype{Image, Video};
int main(int argc, char* argv[])
{
string filename = "short_front.avi";// "C:\\Users\\Jonathan\\Videos\\short_front.mp4"; //"hallways.jpg";
Mat cv_image; //convert to unsigned char * with data
Mat filtImage_;
Mat segmImage_;
Mat whiteImage_;
cv::VideoCapture vid;
vid.open("C:/Users/Jonathan/Desktop/TestMeanShift/TestMeanShift/short_front.avi");
cv::waitKey(1000);
if ( !vid.isOpened() ){
throw "Error when reading vid";
cv::waitKey(0);
return -1;
}
// cv_image = cv::imread(filename);//, CV_LOAD_IMAGE_COLOR);
// if(! cv_image.data){
// std::cerr << "Image Failure: " << std::endl;
// system("pause");
// return -1;
// }
//Mat cv_image_gray;
//cv::cvtColor(cv_image,cv_image_gray,CV_RGB2GRAY);
for (;;)
{
vid >> cv_image;
if ( !cv_image.data)
continue;
cv::imshow("Input",cv_image); //add a normal window here to resizable
}
EDIT: This is a distinct problem from the one listed here because it deals with a specific corner case: VideoCapture and ImageCapture both work, only not VideoCapture with a file. When it doesn't work, the code runs properly, except that the "video" it creates is incomplete as it didn't open properly. Therefore, as the code above does not crash in compile time or run time, the only indicator is bad output (6KB video output file). If you are having issues not with the corner case I am describing but general issues with the above functions in OpenCV, the aforementioned link could help you.

how to view stream sent by me libvlc C/C++

im on Ubuntu 14.04 and I'm trying to write a program that will stream my desktop, using the answer to this: libvlc stream part of screen as an example. However, I don't have another computer readily aviable to see that the stream is going along well, so how can I view that stream on my computer?
libvlc_vlm_add_broadcast(inst, "mybroad", "screen://",
"#transcode{vcodec=h264,vb=800,scale=1,acodec=mpga,ab=128,channels=2,samplerate=44100}:http{mux=ts,dst=:8080/stream}",
5, params, 1, 0)
My program throws no errors, and writes this
[0x7f0118000e18] x264 encoder: using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[0x7f0118000e18] x264 encoder: profile High, level 3.0
[0x7f0118000e18] x264 encoder: final ratefactor: 25.54
[0x7f0118000e18] x264 encoder: using SAR=1/1
[0x7f0118000e18] x264 encoder: using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[0x7f0118000e18] x264 encoder: profile High, level 2.2
So to me, everything seems ok. However, I don't know how to view that stream from my computer- if I open vlc and try to open a network stream, using http:// #:7777 (space on purpose, website does not allow to post such links) I get the invalid host error in its log. This probably is a silly mistake or error on my part, but any help would be greatly appreciated!
if anyone needs it, this is my entire code (I'm using QT 4.8.6):
#include <QCoreApplication>
#include <iostream>
#include <vlc/vlc.h>
#include <X11/Xlib.h>
// #include <QDebug>
using namespace std;
bool ended;
void playerEnded(const libvlc_event_t* event, void *ptr);
libvlc_media_list_t * subitems;
libvlc_instance_t * inst;
libvlc_media_player_t *mp;
libvlc_media_t *media;
libvlc_media_t * stream;
int main(int argc, char *argv[])
{
XInitThreads();
QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
ended = false;
QCoreApplication a(argc, argv);
// the array with parameters
const char* params[] = {"screen-top=0",
"screen-left=0",
"screen-width=640",
"screen-height=480",
"screen-fps=10"};
// Load the VLC engine */
inst = libvlc_new (0, NULL);
if(!inst)
std::cout << "Can't load video player plugins" << std::endl;
cout<< "add broacast: " <<
libvlc_vlm_add_broadcast(inst, "mybroad",
"screen://",
"#transcode{vcodec=h264,vb=800,scale=1,acodec=mpga,ab=128,channels=2,samplerate=44100}:http{mux=ts,dst=:8080/stream}",
5, params, // <= 5 == sizeof(params) == count of parameters
1, 0)<< '\n';
cout<< "poczatek broacastu: " <<libvlc_vlm_play_media(inst, "mybroad")<< '\n';
media = libvlc_media_new_location(inst,http://#:8080/stream");
// Create a media player playing environment
mp = libvlc_media_player_new (inst);
libvlc_media_player_play (mp);
cout<<"szatan!!!"<<endl;
int e;
cin>>e;
/* Stop playing */
libvlc_media_player_stop (mp);
/* Free the media_player */
libvlc_media_player_release (mp);
libvlc_release (inst);
return a.exec();
}
so, i have found the answer- stack overflow wont let me post an answer because I'm new here, so its in the comments! I should have used my IP address when creating media: media = libvlc_media_new_location(inst, "http: //192.168.1.56:8080");(space on purpose so that forum does not hide link) works great! –

Access violation using flann matcher

I'm facing a very annoying problem when I create an object of FalnnBaseMatcher.
The code is the following and it worked fine on ubuntu under eclipse.
#include <iostream>
#include "C:\openCv\opencv\build\include\opencv2\core\core.hpp"
#include "C:\openCv\opencv\build\include\opencv2\highgui\highgui.hpp"
#include "C:\openCv\opencv\build\include\opencv2\imgproc\imgproc.hpp"
#include "C:\openCv\opencv\build\include\opencv2\features2d\features2d.hpp"
#include "C:\openCv\opencv\build\include\opencv2\nonfree\nonfree.hpp"
using namespace std;
using namespace cv;
int main(){
cv::VideoCapture cap("video2.mp4");
if(!cap.isOpened()){ // check if we succeeded
return -1;
}
Mat frame; // creates the object frame
FlannBasedMatcher matcher; //create object matcher
return 0;
}
it compiles but when i run i got an access violation. I tried to split the problem and i figured out that i have this error when i create the object FlannBasedMatcher matcher;
Any help is accepted, thank you very much.
I'm using visual studio express edition 2012 and opencv 242 under windows 7.
Now modifying slightly the code I get an interuption in free.c
/***
*free.c - free an entry in the heap
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* Defines the following functions:
* free() - free a memory block in the heap
*
*******************************************************************************/
#include <cruntime.h>
#include <malloc.h>
#include <winheap.h>
#include <windows.h>
#include <internal.h>
#include <mtdll.h>
#include <dbgint.h>
#include <rtcsup.h>
/***
*void free(pblock) - free a block in the heap
*
*Purpose:
* Free a memory block in the heap.
*
* Special ANSI Requirements:
*
* (1) free(NULL) is benign.
*
*Entry:
* void *pblock - pointer to a memory block in the heap
*
*Return:
* <void>
*
*******************************************************************************/
void __cdecl _free_base (void * pBlock)
{
int retval = 0;
if (pBlock == NULL)
return;
RTCCALLBACK(_RTC_Free_hook, (pBlock, 0));
retval = HeapFree(_crtheap, 0, pBlock);
if (retval == 0)
{
errno = _get_errno_from_oserr(GetLastError());
}
}
The interruption is in: if (retval == 0)
SOLVED!
I rebuilt openCv for VisualStudio 2012 using cMake and now works fine.

How to decode an animated gif File in MFC2010

Deal all,
I need to decode an animated gif format picture into some bitmap files in MFC2010. Is there any library to decode a gif picture? I cannot use GDIPlus because the program has to run on windows XP. I do appreciate if someone provides me with a library, Activex, dll or anything similar.
Many Thanks,
Shervin Zargham
It's pretty simple using ImageMagick's C++ API (Magick++) :
/* list of Image to store the GIF's frames */
std::vector<Magick::Image> imageList;
/* read all the frames of the animated GIF */
Magick::readImages( &imageList, "animated.gif" );
/* optionnally coalesce the frame sequence depending on the expected result */
Magick::coalesceImages( &imageList, imageList.begin(), imageList.end());
/* store each frame in a separate BMP file */
for(unsigned int i = 0; i < imageList.size(); ++i) {
std::stringstream ss;
ss << "frame" << i << ".bmp";
imageList[i].write(ss.str());
}
WIC (included in Vista, available for XP) offers CLSID_WICGifDecoder, a COM component.
Try this using ImageMagick's C++ API (Magick++) ,tested on VS210:
#include <Magick++.h>
#include <string>
#include <iostream>
#include <list>
using namespace std;
using namespace Magick;
void kk(char * nombre, char *ext)
{
/* list of Image to store the GIF's frames */
std::list<Magick::Image> imageList;
/* read all the frames of the animated GIF */
Magick::readImages( &imageList, nombre );
/* compone las diferencias para obtener los cuadros reales */
Magick::coalesceImages(&imageList,imageList.begin( ),imageList.end( ));
/* store each frame in a separate BMP file */
list <Magick::Image>::iterator it;
int i=1;
for ( it = imageList.begin( ); it != imageList.end( ); it++ , i++)
{
std::string name = "frame" + to_string((_Longlong)(i)) + ext ;
it->write(name);
}
}
int main( int /*argc*/, char ** argv)
{
// Initialize ImageMagick install location for Windows
InitializeMagick(*argv);
try {
kk("luni0.gif", ".png"); // using ".bmp", ".jpg", ".png", OK
return 0;
}
catch( exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
}
It's been a long time, but I recall once using OleLoadPicture to open GIF and PNG files on old versions of Windows, though the documentation seems to suggest that it's only for BMP, ICO, and WMF.

how to access a webcam that was symlinked by udev in opencv

I am developing an application that requires multiple webcams. In order to make sure that the correct webcam is used for each part of the application, I created some udev rules that SYMLINK the webcam to a specific name, depending on the serial number.
This works great, and I can access the camera by that name using VLC and a variety of other applications.
But when I try to access the camera by that name (or the non-syminked name given by linux) using OpenCV and python, I can't read a frame from the camera and my program hangs. The camera is opened successfully. I've created a sample application in C++ to test if it was perhaps a python/opencv related bug, but the same thing happens in C++ too.
Here is my C++ test application that doesn't work:
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main (int argc, const char * argv[])
{
VideoCapture cap("/dev/my_custom_name");
if (!cap.isOpened())
return -1;
cout << "Opened..." << endl;
Mat img;
namedWindow("video capture", CV_WINDOW_AUTOSIZE);
while (true)
{
cout << "Trying..." << endl;
cap >> img;
cout << "Got" << endl;
imshow("video capture", img);
if (waitKey(10) >= 0)
break;
}
return 0;
}
I get the Opened... and Trying... messages, but not the Got message.
Any ideas on how to resolve this issue?
(This is all on linux btw).
Thanks
I figured this out. When I opened the capture in VLC, I noticed that it preixed the filename with v4l2://. When I did the same in my application, it worked!
So to reference above, "/dev/my_custom_name" should become "v4l2:///dev/my_custom_name".