migrating code from Microsoft Visual C++ to debian (raspberry) - linux

My English is not very good (im from Chile) but will try to explain in the best way possible (+ google translator :P)
well im working in Microsoft Visual C++ 2010 express and I need to migrate my opencv code to Linux to work on a rapsberry
Here the code:
#include "StdAfx.h"
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv\cv.h>
//#include <iostream>
using namespace cv;
int main( int argc, char** argv )
{
//Variable
CvCapture* capture = 0;
IplImage* frame = 0;
IplImage* frame_black = 0;
IplImage* frame_blue = 0;
IplImage* frame_red = 0;
//IplImage* red_gray = 0;
//Verifica Camara
capture = cvCaptureFromCAM(1);
if( !cvGrabFrame( capture )){
printf("error cámara");
exit(0);
}
//Comienza
for(;;){
// Captura imagen from camara
frame = cvQueryFrame(capture);
if( !frame ) break;
// filtro negro
frame_black = cvCreateImage(cvGetSize(frame),8,3);
CvScalar r,g;
for(int i=0;i<(frame->height);i++){
for(int j=0;j<(frame->width);j++){
r=cvGet2D(frame,i,j);
if((r.val[2]<80)&&(r.val[1]<80)&&(r.val[0]<80)){
g.val[2]=0;
g.val[1]=0;
g.val[0]=0;
cvSet2D(frame_black,i,j,g);
}
else{
g.val[2]=255;
g.val[1]=255;
g.val[0]=255;
cvSet2D(frame_black,i,j,g);
}
}
}
// filtro azul
frame_blue = cvCreateImage(cvGetSize(frame),8,3);
CvScalar s,c;
for(int i=0;i<(frame->height);i++){
for(int j=0;j<(frame->width);j++){
s=cvGet2D(frame,i,j);
if((s.val[2]<100)&&(s.val[1]<100)&&(s.val[0]>100)){
c.val[2]=0;
c.val[1]=0;
c.val[0]=255;
cvSet2D(frame_blue,i,j,c);
}
else{
c.val[2]=255;
c.val[1]=255;
c.val[0]=255;
cvSet2D(frame_blue,i,j,c);
}
}
}
// filtro rojo
frame_red = cvCreateImage(cvGetSize(frame),8,3);
CvScalar p,q;
for(int i=0;i<(frame->height);i++){
for(int j=0;j<(frame->width);j++){
p=cvGet2D(frame,i,j);
if((p.val[2]>100)&&(p.val[1]<100)&&(p.val[0]<100)){
q.val[2]=255;
q.val[1]=0;
q.val[0]=0;
cvSet2D(frame_red,i,j,q);
}
else{
q.val[2]=255;
q.val[1]=255;
q.val[0]=255;
cvSet2D(frame_red,i,j,q);
}
}
}
/* filtro hough
red_gray = cvCreateImage(cvGetSize(frame),8,1);
cvCvtColor( frame_red, red_gray, CV_BGR2GRAY);
cvSmooth(red_gray, red_gray, CV_BLUR,3);
CvMemStorage* storage_var = cvCreateMemStorage(0);
CvSeq* results = cvHoughCircles(red_gray, storage_var , CV_HOUGH_GRADIENT , 2, red_gray->height/3 );
// reemplaza
for( int i = 0; i < results->total; i++ ){
float* p = (float*) cvGetSeqElem( results, i );
CvPoint pt = cvPoint( cvRound( p[0] ), cvRound( p[1] ));
cvCircle(red_gray,pt,cvRound( p[2] ),cvScalar(0,0,255),1.8);
}
*/
// mostrar en ventana
cvShowImage("ventana",frame_black);
if( cvWaitKey( 10 ) >= 0 )
break;
}
//Libera de memoria
cvReleaseCapture( &capture);
cvReleaseImage( &frame);
cvReleaseImage( &frame_black);
cvReleaseImage( &frame_blue);
cvReleaseImage( &frame_red);
//cvReleaseImage( &red_gray);
return 0;
}
copying and pasting the code into a file "codigo.c" and compiling (in linux terminal) with
gcc codigo.c -o codigo $(pkg-config --cflags --libs opencv)
I have the following error
codigo.c:3:21 fatal error: StdAfx.h: No such file or directory
compilation terminated.
well, google told me that StdAfx.h is a header of microsoft visual c++
and here i crash :l
i dont know what can i do now
I hope someone can tell me some way to go to fix this problem
thx to all

As your code does not depend on anything other than opencv, you can just leave out the stdafx header. it's a feature of visual studio that you dont need here.
( see Purpose of stdafx.h )
it compiles fine on my machine. with:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv/cv.h>
note the "/". please use these instead of backslashes here, or unix machines will complain.
also: use g++ to compile this code, not gcc.

Related

Unhandled exception , access violation in opencv cvCaptureFromCAM using Visual c++

I am trying to build a program in Opencv that captures a video and saves it to a file. However, after repeated efforts I continue to get this error : Unhandled exception at 0x201e8efb in basic.exe: 0xC0000005 Access violation, where basic.cpp is my file name.
The same occurs when trying to capture an image.
I have already tried changing cvCaptureFromCAM parameters to CV_CAP_ANY/0/-1/-2/1/2..but none of these worked out.My webcam, works perfectly well for others applications and i have tested it online.
Any help would be greatly appreciated .Thanks in advance.
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "C:\opencv\build\include\opencv2\core\core.hpp"
#include "C:\opencv\build\include\opencv2\highgui\highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
void main( ){
CvCapture *capture = cvCaptureFromCAM( 0 );
int width = ( int )cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH );
int height = ( int )cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT );
CvVideoWriter *writer = cvCreateVideoWriter( "myCamCapture.avi", -1, 30, cvSize( width, height ) );
cvNamedWindow("camopen", CV_WINDOW_AUTOSIZE);
IplImage *frame = 0;
while( 1 )
{
frame = cvQueryFrame( capture );
cvShowImage("d",frame);
cvWriteFrame( writer, frame );
char c = cvWaitKey( 30 );
if( c == 27 ) break;
}
}
please, since you're a beginner, don't start with the deprecated c-api, use the c++ one instead.
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
using namespace cv;
int main()
{
VideoCapture cap(0);
while( cap.isOpened() )
{
Mat frame;
if ( ! cap.read(frame) )
break;
imshow("lalala",frame);
int k = waitKey(10);
if ( k==27 )
break;
}
return 0;
}
regarding your error: please triple-check the libs you're linking (compiler version, debug/release, 32/64bit). you're not allowed to mix different settings there

error:capture is NULL in opencv in window7

I've seen other posts here similar to this question and even goggled and attempted to try every possible method stated, but neither of them worked for me.
following code is just to capture the image infinitely from webcam and Code is building successfully
getting error "error:capture is NULL".
Does opencv2.2.0 is supported for windows 7, i have seen in many posts where it is mentioned to use Direct show for video capturing in window 7
#include<opencv/cxcore.h>
#include<opencv/highgui.h>
#include<opencv/cxcore.h>
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char* argv[])
{
CvSize size640x480 = cvSize(640,480);
CvCapture* p_capWebcam;
IplImage* p_imgOriginal;
p_capWebcam=cvCaptureFromCAM(0);//i tried p_capWebcam=cvCaptureFromCAM(CV_CAP_ANY)
//i tried index from -1 to 10 but nothing worked
if(p_capWebcam==NULL)
{
printf("error:capture is NULL");
getchar();
return -1;
}
cvNamedWindow("Original",CV_WINDOW_AUTOSIZE);
while(1)
{
p_imgOriginal=cvQueryFrame(p_capWebcam);
if(p_imgOriginal=NULL)
{
printf("error :frame is NULL \n");
break;
}
cvWaitKey(10);
cvShowImage("Original",p_imgOriginal);
}
}
IDE is Microsoft Visual C++ 2010 Express,
Webcamera(Frontech) usb2.0 supports following formats
{'YUY2_160x120' 'YUY2_176x144' 'YUY2_320x240' 'YUY2_352x288' 'YUY2_640x480'}
you're lacking a call to cvWaitKey(10); after the cvShowImage() (thus your window does not get updated).
and please, move over to the c++ api, the outdated c-api won't be supported for long.
so, the whole thing should look more like this:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
using namespace cv;
int main()
{
VideoCapture cap(0);
while( cap.isOpened() )
{
Mat frame;
if ( ! cap.read(frame) )
break;
imshow("lalala",frame);
int k = waitKey(10);
if ( k==27 )
break;
}
return 0;
}

SDL2/SDL.h causing undefined references in Non-SDL code

I've been having an awfully strange problem that I cannot seem to grasp. I'm almost convinced that this is a compiler bug.
xTech : xIncludes.hh
#ifndef _xIncludes_
#define _xIncludes_
#define SDL_MAIN_HANDLED
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
#include <vector>
#include <SDL2/SDL.h>
#if defined _WIN32
#include <winsock.h>
#endif
#endif
xTech : xSound.cc
#include "xSound.hh"
int xOGGStreamSource::_stream(ALuint Buffer) {
char data[BufferSize];
int size = 0;
int section;
int result;
while (size < BufferSize) {
result = ov_read(&_oggstream, data + size, BufferSize - size, 0, 2, 1, &section);
if (result > 0)
size += result;
else
if (result < 0)
return result;
else
break; //This seems a little redundant.... deal with it after it works.
}
if (size == 0) return 0;
alBufferData(Buffer, _format, data, size, _vorbisinfo->rate);
return 1;
}
void xOGGStreamSource::_empty() {
int queued;
alGetSourcei(_source, AL_BUFFERS_QUEUED, &queued);
while (queued--) {
ALuint Buffer;
alSourceUnqueueBuffers(_source, 1, &Buffer);
}
}
int xOGGStreamSource::Open(xString path) {
int result;
_oggfile = xOpenFile(path, "rb");
if (_oggfile.Buffer == NULL) {
xLogf("Audio", "Error in OGG File '%s', file does not exist.", path);
return -3;
}
if (result = ov_open(_oggfile.Buffer, &_oggstream, NULL, 0) < 0) {
xLogf("Audio", "Error in OGG File '%s', file is non-OGG.", path);
xCloseFile(_oggfile);
return -2;
}
_vorbisinfo = ov_info(&_oggstream, -1);
_vorbiscomment = ov_comment(&_oggstream, -1);
if (_vorbisinfo->channels == 1)
_format = AL_FORMAT_MONO16;
else
_format = AL_FORMAT_STEREO16;
alGenBuffers(2, _buffers);
alGenSources(1, &_source);
return 1;
}
void xOGGStreamSource::Close() {
alSourceStop(_source);
_empty();
alDeleteSources(1, &_source);
alDeleteBuffers(1, _buffers);
ov_clear(&_oggstream);
}
int xOGGStreamSource::Playback() {
if (Playing()) return 1;
if (!_stream(_buffers[0])) return 0;
if (!_stream(_buffers[1])) return 0;
alSourceQueueBuffers(_source, 2, _buffers);
alSourcePlay(_source);
return 1;
}
int xOGGStreamSource::Playing() {
ALenum state;
alGetSourcei(_source, AL_SOURCE_STATE, &state);
return (state == AL_PLAYING);
}
int xOGGStreamSource::Update(xVec3f_t Pos, xVec3f_t Vloc, xVec3f_t Dir, float Vol) {
int processed;
int active = 1;
alSource3f(_source, AL_POSITION, Pos.X, Pos.Y, Pos.Z);
alSource3f(_source, AL_VELOCITY, Vloc.X, Vloc.Y, Vloc.Z);
alSource3f(_source, AL_DIRECTION, Dir.X, Dir.Y, Dir.Z);
alSourcef (_source, AL_GAIN, Vol);
alSourcei (_source, AL_SOURCE_RELATIVE, AL_TRUE);
alGetSourcei(_source, AL_BUFFERS_PROCESSED, &processed);
while(processed--) {
ALuint Buffer;
alSourceUnqueueBuffers(_source, 1, &Buffer);
active = _stream(Buffer);
alSourceQueueBuffers(_source, 1, &Buffer);
}
return active;
}
xSound::xSound(xOGGStreamSource xss) { _source = xss; }
int xSound::PlaySound(float Volume, xVec3f_t Location) {
if (!_source.Playback()) return -3;
while(_source.Update(Location, xVec3f_t(0,0,0), xVec3f_t(0,0,0), Volume)) {
if (!_source.Playing()) {
if (!_source.Playback()) return -2;
else return -1;
}
}
_source.Close();
return 1;
}
xSoundManager::xSoundManager(){}
int xSoundManager::Init() {
_device = alcOpenDevice(NULL);
if (!_device) return -2;
_context = alcCreateContext(_device, NULL);
if (alcMakeContextCurrent(_context) == ALC_FALSE || !_context) return -1;
if (!Volume) {
xLogf("Error", "Volume in Audio is not set properly. Setting to default");
Volume = DEFAULT_VOLUME;
}
alListenerf(AL_GAIN, Volume);
if (!BufferSize) {
xLogf("Error", "Buffer size in Audio is not set properly. Setting to default");
BufferSize = DEFAULT_BUFFER_SIZE;
}
return 0;
}
xSound* xSoundManager::LoadOGG(xString file) {
xOGGStreamSource ogg;
if (ogg.Open(file) < 0) return NULL;
return new xSound(ogg);
}
xTechLibTest : main.cc
int main() {
xSetLogFile("xTechLibTest.log");
xSoundManager* audio = new xSoundManager();
if (audio->Init() < 0) return -1;
xSound* testsound1 = audio->LoadOGG("testsound.ogg");
if (testsound1 == NULL) return -2;
testsound1->PlaySound(1.0, xVec3f_t(1.0,0.5,0.3));
}
The above code and everything associated with it (string implementations, etc) work fine, no problems at all. That is until I include SDL.h; I get undefined references for every function I defined, when the compiler could find them with no problem before. It seems that the mere inclusion of SDL.h completely nullifies any definition I make. Any ideas what's going on here?
Have you properly included the linkage to the SDL libraries?
If you have built the binaries yourself, you need to include the path and library. On a linux system, if you have built the static libraries yourself, you will have a binary called libSDL2.a, however to link you need to specify SDL2 as your linked library.
Also as a side note, do you have a redundant include guard on your xsound.h file( via #ifdef _xsound_ ... ) ?
p.s. It will help the other users if you specify what how your environment is setup; compiler, system os, IDE.
It would be useful to see the output from your compiler/linker.
I've had similar problems with network related code when using Cygwin on a windows machine. I've had sockets working fine without SDL, as soon as I include SDL, the whole lot breaks with messages saying that certain header files and references can't be found.
I'm not certain, but I think it has something to do with the way that SDL has it's own main macros (here is a post about it here - simple tcp echo program not working when SDL included?).
I may be wrong, but is this similar to what you are seeing?

How to play and detect an object using captured video in background subtractor model?

everyone.! I am using opencv2.4.2. actually I am doing project on object detection. I tried using BackgroundSubtractorMOG model.
But I am not able to load video file from my computer. While running on real time this below code for segmentation works fine.
I have implemented using frame differencing method for object detection. Now I want to segment whole object from the background. I have static background. so can anybody help me in below code how to segment object from captured video. also how to load a video file?
thank you.
#include "stdafx.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/contrib/contrib.hpp"
#include "conio.h"
#include "time.h"
#include "opencv/cvaux.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/calib3d/calib3d.hpp"
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
//IplImage* tmp_frame;
//std::string arg = argv[1];
//VideoCapture capture();
cv::VideoCapture cap;
/*CvCapture *cap =cvCaptureFromFile("S:\\offline object detection database\\SINGLE PERSON Database\\video4.avi");
if(!cap){
printf("Capture failure\n");
return -1;
}
IplImage* frame=0;
frame = cvQueryFrame(cap);
if(!frame)
return -1;*/
bool update_bg_model = true;
if( argc < 2 )
cap.open(0);
else
cap.open(std::string(argv[1]));
if( !cap.isOpened() )
{
printf("can not open camera or video file\n");
return -1;
}
Mat tmp_frame, bgmask;
cap >> tmp_frame;
if(!tmp_frame.data)
{
printf("can not read data from the video source\n");
return -1;
}
namedWindow("video", 1);
namedWindow("segmented", 1);
BackgroundSubtractorMOG bgsubtractor;
for(;;)
{
//double t = (double)cvGetTickCount();
cap >> tmp_frame;
if( !tmp_frame.data )
break;
bgsubtractor(tmp_frame, bgmask, update_bg_model ? -1 : 0);
//t = (double)cvGetTickCount() - t;
//printf( "%d. %.1f\n", fr, t/(cvGetTickFrequency()*1000.) );
imshow("video", tmp_frame);
imshow("segmented", bgmask);
char keycode = waitKey(30);
if( keycode == 27 ) break;
if( keycode == ' ' )
update_bg_model = !update_bg_model;
}
return 0;
}
The video loading in opencv works for me. To load a video you can try something like this. Once you have captured frame you either do processing in the loop or can call a separate function.
std::cout<<"Video File "<<argv[1]<<std::endl;
cv::VideoCapture input_video(argv[1]);
namedWindow("My_Win",1);
Mat cap_img;
while(input_video.grab())
{
if(input_video.retrieve(cap_img))
{
imshow("My_Win", cap_img);
/* Once you have the image do all the processing here */
/* Or Call your image processing function */
waitKey(1);
}
}
or You can do something
int main(int argc, char*argv[])
{
char *my_file = "C:\\vid_an2\\desp_me.avi";
std::cout<<"Video File "<<my_file<<std::endl;
cv::VideoCapture input_video;
if(input_video.open(my_file))
{
std::cout<<"Video file open "<<std::endl;
}
else
{
std::cout<<"Not able to Video file open "<<std::endl;
}
namedWindow("My_Win",1);
namedWindow("Segemented", 1);
Mat cap_img;
for(;;)
{
input_video >> cap_img;
imshow("My_Win", cap_img);
waitKey(0);
}
return 0;
}

OpenCv and Visual C++ Eyedetection

I'm writing a software for eye detection in a webcam stream. I'm using OpenCV in Visual Studio but when I load the haarcascade file, I get an unhandled exception and in the output:
OpenCV error: NULL pointer <NULL or empty buffer> in unknow function,
file ....persistence.cpp
Here is the code:
#include <opencv2/core/core.hpp>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
/** Function Headers */
void detectAndDisplay( Mat frame );
/** Global variables */
String face_cascade_name = "C:/opencv/data/haarcascades/haarcascade_frontalface_alt.xml";
String eyes_cascade_name = "C:/opencv/data/haarcascades/haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
string window_name = "Capture - Face detection";
RNG rng(12345);
/** #function main */
int main( int argc, const char** argv )
{
CvCapture* capture;
Mat frame;
int a;
//-- 1. Load the cascades
if (!face_cascade.load( face_cascade_name) ) {
cout << "Couldn't load face_cascade" << endl;
exit(-1);
}
if (!eyes_cascade.load( eyes_cascade_name) ) {
cout << "Couldn't load face_cascade" << endl;
exit(-1);
}
cout << "Loaded cascade" << endl;
//-- 2. Read the video stream
capture = cvCaptureFromCAM( -1 );
if( capture )
{
while( true )
{
frame = cvQueryFrame( capture );
//-- 3. Apply the classifier to the frame
if( !frame.empty() )
{ detectAndDisplay( frame ); }
else
{ printf(" --(!) No captured frame -- Break!"); break; }
int c = waitKey(10);
if( (char)c == 'c' ) { break; }
}
}
return 0;
}
/** #function detectAndDisplay */
void detectAndDisplay( Mat frame )
{
std::vector<Rect> faces;
Mat frame_gray;
cvtColor( frame, frame_gray, CV_BGR2GRAY );
equalizeHist( frame_gray, frame_gray );
//-- Detect faces
face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( int i = 0; i < faces.size(); i++ )
{
Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 );
ellipse( frame, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360,
Scalar( 255, 0, 255 ), 4, 8, 0 );
Mat faceROI = frame_gray( faces[i] );
std::vector<Rect> eyes;
//-- In each face, detect eyes
eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30,30) );
for( int j = 0; j < eyes.size(); j++ )
{
Point center( faces[i].x + eyes[j].x + eyes[j].width*0.5, faces[i].y + eyes[j].y + eyes[j].height*0.5 );
int radius = cvRound( (eyes[j].width + eyes[j].height)*0.25 );
circle( frame, center, radius, Scalar( 255, 0, 0 ), 4, 8, 0 );
}
}
//-- Show what you got
imshow( window_name, frame );
}
I've done all the inclusion to make OpenCV working with Visual Studio and the cascade classifier are in the correct path so I don't know why this code don't work.
Ah, I've exception too when I try the sample facerecognition.cpp.
Any help is appreciated.
EDIT:
I've tried with the help of Barnabas but the exception is the same.
But maybe I found out something. If I delete the code
if (!eyes_cascade.load( eyes_cascade_name) ) {
cout << "Couldn't load face_cascade" << endl;
exit(-1);
}
The exception comes after the opening of webcam's software and if I continue the result is a frame (only one) where I can see my face recognized. So if I delete the control on the loading of the eye cascade classifier, the problem delay.
New ideas?
Basically, the problem is that you are mixing up the C++ and the C interface.
The camera capture is not CvCapture*. Here is how to capture from webcam (or from video-stream) correctly:
using namespace cv;
VideoCapture cap(0); // 0 for webcam input
if(cap.isOpened()) // use this instead of if( capture )
cap >> frame; // instead of cvQueryFrame
This issue was driving me insane when I realised it was possibly something to do with the program using the wrong dlls for some reason; I haven't figured out why yet. My hunch was that my OPENCV_DIR enviroment variable was set to on older version of OpenCV but having checked I have set it to the newer version.
Any how, to get working code in VS 2012 (vc11) I did the following:
open the properties page and go to Configuration Properties > Debugging and add to the Environement variable "path=C:/OpenCV2_4_5/build/x86/vc11/bin;%PATH%" without the quotation marks. Obviously, your path to that bin folder may be different.
Hope this helps.

Resources