CCCPaste

Capture OpenCV to SDL

#include 
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
#include 
using namespace cv;
//Build Flags
//g++ -Wall -g -o "%e" "%f" -lSDL -lSDL_image -lSDL_ttf  -lSDL_mixer -lGL -lGLU -lglut -lGLEW -lXi  -lXmu `pkg-config --cflags --libs opencv`
SDL_Surface* image = NULL;
SDL_Surface* backbuffer = NULL;
SDL_Surface* asurface = NULL;
//pass in an opencv image, get a sureface out
//https://wiki.libsdl.org/SDL_CreateRGBSurfaceFrom
//http://stackoverflow.com/questions/22702630/converting-cvmat-to-sdl-texture
SDL_Surface* convertCV_MatToSDL_Texture(const cv::Mat &frame){
    IplImage opencvimg2 = (IplImage)frame;
    IplImage* opencvimg = &opencvimg2;

     //Convert to SDL_Surface
    asurface = SDL_CreateRGBSurfaceFrom(
                         (void*)opencvimg->imageData,
                         opencvimg->width, opencvimg->height,
                         opencvimg->depth*opencvimg->nChannels,
                         opencvimg->widthStep,
                         0xff0000, 0x00ff00, 0x0000ff, 0);

    if(asurface == NULL){
        printf("Couldn't convert Mat to Surface.");
        return NULL;
    }    else    {
        printf("SUCCESS! conversion!");
        return asurface;
    }

    cvReleaseImage(&opencvimg);

}
int main(int argc, char **argv){
	
    VideoCapture cap(0); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;
        
        
    //Init SDL
    if(SDL_Init(SDL_INIT_EVERYTHING) < 0){
        printf("SDL failed to initialize!");
        SDL_Quit();
        return 0;
    }

    backbuffer = SDL_SetVideoMode(800, 600, 32, SDL_SWSURFACE);

    SDL_WM_SetCaption("SDL!!!", NULL);

    //Load the image
    //image = SDL_LoadBMP("graphics/image.bmp" );
    Mat frame;
    cap >> frame; // get a new frame from camera
    //imshow("edges", frame);
    image = convertCV_MatToSDL_Texture(frame);
    
    if(image == NULL){
        printf("Image failed to load!\n");
        SDL_Quit();
        return 0;
    }

    //Draw the image
    SDL_BlitSurface(image, NULL, backbuffer, NULL );
    SDL_Flip(backbuffer);

    //Wait
    SDL_Delay(3000);

    //Finish
    SDL_FreeSurface( image);
    SDL_Quit();

    return 1;
}