bac
bac

Reputation: 93

Call Python from C++ OpenCV 3.0

So i was using PiCam to get video feed, but figured i could try to get the stream to C++ for processing.

Python code:

import time
import picamera
import picamera.array
import cv2

with picamera.PiCamera() as camera:
    camera.start_preview()
    time.sleep(2)
    with picamera.array.PiRGBArray(camera) as stream:
        camera.capture(stream, format='bgr')
        # At this point the image is available as stream.array
        image = stream.array

So, what to do in my .cpp file? I've been looking into boost::python, but their documentation sucks..

Any benefits to send numpy array instead of converting to Cv.Mat directly in the Python code and then call it from C++? Like this.

Any questions? All help appreciated!

Edit: Forgot to mention, have tried this without success. Found pyopencv_to() and pyopencv_from() now, but not sure how to use? Sorry, new to this. (Would have linked the pyopencv_ above, but not allowed to post more than two links.)

Upvotes: 3

Views: 814

Answers (1)

bac
bac

Reputation: 93

I solved it myself by piping. Thought I should share my solution:

C++ side:

union pipe
{
    uint8_t image[height] [width] [colors];
    uint8_t data [height * width * colors];
} raw;

int main(){
    // Reads in the raw data
    fread(&raw.image, 1, sizeof(raw.data), stdin);

    // Rebuild raw data to cv::Mat
    image = Mat(height, width, CV_8UC3, *raw.image);
}

Python side: (just added this at end of code above)

sys.stdout.buffer.write(image.tostring())

Running it by typing this in terminal:

python img.py | ./img

Works really well for me!

Upvotes: 3

Related Questions