logo
down
shadow

Call Python from C++ OpenCV 3.0


Call Python from C++ OpenCV 3.0

By : Cesium
Date : November 22 2020, 02:42 PM
This might help you Okay, so I solved it myself by piping. Thought I should share my solution:
C++ side:
code :
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);
}
sys.stdout.buffer.write(imgage.tostring())
python img.py | ./img


Share : facebook icon twitter icon
Function call works in C but Segfaults in Python when accessing Prosilica GigE Camera with Python using OpenCV

Function call works in C but Segfaults in Python when accessing Prosilica GigE Camera with Python using OpenCV


By : Darrin Maule
Date : March 29 2020, 07:55 AM
Hope that helps I fixed the problem, the only difference between the C code and the Python code was the argument passed to cvCreateCameraCapture()(capture.open() in Python). Passing a 0 into this function(as I did in Python) should make it scan for any video device OpenCV supports, which it did. Passing CV_CAP_PVAPI(as I did in C) should limit this search to only Prosilica devices. While these should yeild exactly the same results(they both found the same camera), when passing in a 0 the camera did not get initialized and wasn't ready to accept tPvFrames in the queue. Passing an 800 into capture.open() fixed the problem, as 800 is the value of CV_CAP_PVAPI.
Call C++ opencv functions from Python ( Send a cv :: Mat to C++ dll which is using opencv )

Call C++ opencv functions from Python ( Send a cv :: Mat to C++ dll which is using opencv )


By : Ari Gonzalez
Date : March 29 2020, 07:55 AM
I wish this help you You can have a look at the OpenCV Python wrapper. In the OpenCV folder in modules/python/src2/cv2.cpp (depending on the version, I use OpenCV 2.4) there are some functions called pyopencv_to used by the OpenCV Python wrapper. One of those is used to convert PyObject to cv::Mat. Your "FromPython" function needs to get PyObject as input. I personally use boost::python::object to pass the numpy arrays returned by the Python OpenCV functions to the C++ function/class. You should end up having something like this in C++:
code :
///PythonToOCV.h

#ifndef __PYTHONTOOCV_H_INCLUDED__
#define __PYTHONTOOCV_H_INCLUDED__

#include <iostream>
#include <Python.h>
#include <boost/python.hpp>
#include "numpy/ndarrayobject.h"
#include "opencv2/core/core.hpp"

/////////////////////////////////////////////////////////////////////////////
/// \brief Import Numpy array. Necessary to avoid PyArray_Check() to crash
void doImport( );

int failmsg( const char *fmt, ... );

static size_t REFCOUNT_OFFSET = ( size_t )&((( PyObject* )0)->ob_refcnt ) +
( 0x12345678 != *( const size_t* )"\x78\x56\x34\x12\0\0\0\0\0" )*sizeof( int );

static inline PyObject* pyObjectFromRefcount( const int* refcount )
{
return ( PyObject* )(( size_t )refcount - REFCOUNT_OFFSET );
}

static inline int* refcountFromPyObject( const PyObject* obj )
{
return ( int* )(( size_t )obj + REFCOUNT_OFFSET );
}

class NumpyAllocator : public cv::MatAllocator
{
public:
NumpyAllocator( ) { }
~NumpyAllocator( ) { }

void allocate( int dims, const int* sizes, int type, int*& refcount,
uchar*& datastart, uchar*& data, size_t* step );

void deallocate( int* refcount, uchar* datastart, uchar* data );
};


/////////////////////////////////////////////////////////////////////////////
/// \brief Convert a numpy array to a cv::Mat. This is used to import images
/// from Python.
/// This function is extracted from opencv/modules/python/src2/cv2.cpp
/// in OpenCV 2.4
int pyopencv_to( const PyObject* o, cv::Mat& m, const char* name = "<unknown>", bool allowND=true );
#endif //__PYTHONTOOCV_H_INCLUDED__

///PythonToOCV.cpp

#include "PythonToOpenCV.h"

void doImport( )
{
    import_array( );
}

int failmsg( const char *fmt, ... )
{
    char str[1000];

    va_list ap;
    va_start( ap, fmt );
    vsnprintf( str, sizeof( str ), fmt, ap );
    va_end( ap );
    PyErr_SetString( PyExc_TypeError, str );
    return 0;
}

void NumpyAllocator::allocate( int dims, const int* sizes, int type, int*& refcount, uchar*& datastart, uchar*& data, size_t* step )
{
    int depth = CV_MAT_DEPTH( type );
    int cn = CV_MAT_CN( type );
    const int f = ( int )( sizeof( size_t )/8 );
    int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
                  depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
                  depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
                  depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
    int i;
    npy_intp _sizes[CV_MAX_DIM+1];
    for( i = 0; i < dims; i++ )
        _sizes[i] = sizes[i];
    if( cn > 1 )
    {
    /*if( _sizes[dims-1] == 1 )
         _sizes[dims-1] = cn;
    else*/
        _sizes[dims++] = cn;
    }
    PyObject* o = PyArray_SimpleNew( dims, _sizes, typenum );
    if( !o )
    CV_Error_(CV_StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
    refcount = refcountFromPyObject(o);
    npy_intp* _strides = PyArray_STRIDES(o);
    for( i = 0; i < dims - (cn > 1); i++ )
        step[i] = (size_t)_strides[i];
    datastart = data = (uchar*)PyArray_DATA(o);

}

void NumpyAllocator::deallocate( int* refcount, uchar* datastart, uchar* data )
{
    if( !refcount )
       return;
    PyObject* o = pyObjectFromRefcount(refcount);
    Py_INCREF(o);
    Py_DECREF(o);
}

// Declare the object
NumpyAllocator g_numpyAllocator;

int pyopencv_to(const PyObject* o, cv::Mat& m, const char* name, bool allowND )
{
    // to avoid PyArray_Check() to crash even with valid array
    doImport( );

    if(!o || o == Py_None)
    {
        if( !m.data )
            m.allocator = &g_numpyAllocator;
        return true;
    }

    if( !PyArray_Check(o) )
    {
        failmsg("%s is not a numpy array", name);
        return false;
    }

    // NPY_LONG (64 bit) is converted to CV_32S (32 bit)
    int typenum = PyArray_TYPE(o);
    int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S :
        typenum == NPY_USHORT ? CV_16U : typenum == NPY_SHORT ? CV_16S :
        typenum == NPY_INT || typenum == NPY_LONG ? CV_32S :
        typenum == NPY_FLOAT ? CV_32F :
        typenum == NPY_DOUBLE ? CV_64F : -1;

    if( type < 0 )
    {
        failmsg("%s data type = %d is not supported", name, typenum);
        return false;
    }

    int ndims = PyArray_NDIM(o);
    if(ndims >= CV_MAX_DIM)
    {
        failmsg("%s dimensionality (=%d) is too high", name, ndims);
        return false;
    }

    int size[CV_MAX_DIM+1];
    size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type);
    const npy_intp* _sizes = PyArray_DIMS(o);
    const npy_intp* _strides = PyArray_STRIDES(o);
    bool transposed = false;

    for(int i = 0; i < ndims; i++)
    {
        size[i] = (int)_sizes[i];
        step[i] = (size_t)_strides[i];
    }

    if( ndims == 0 || step[ndims-1] > elemsize ) {
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }

    if( ndims >= 2 && step[0] < step[1] )
    {
        std::swap(size[0], size[1]);
        std::swap(step[0], step[1]);
        transposed = true;
    }

    if( ndims == 3 && size[2] <= CV_CN_MAX && step[1] == elemsize*size[2] )
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }

    if( ndims > 2 && !allowND )
    {
        failmsg("%s has more than 2 dimensions", name);
        return false;
    }

    m = cv::Mat(ndims, size, type, PyArray_DATA(o), step);

    if( m.data )
    {
        m.refcount = refcountFromPyObject(o);
        m.addref(); // protect the original numpy array from deallocation
        // (since Mat destructor will decrement the reference counter)
    };
    m.allocator = &g_numpyAllocator;

    if( transposed )
    {
        cv::Mat tmp;
        tmp.allocator = &g_numpyAllocator;
        transpose(m, tmp);
        m = tmp;
    }
    return true;
}
/// fromPython.h

#ifndef __FROMPYTHON_H_INCLUDED__
#define __FROMPYTHON_H_INCLUDED__

#include "PythonToOCV.h"
#include <boost/python.hpp>

int fromPython( boost::python::object &frame );
#endif //__FROMPYTHON_H_INCLUDED__



/// fromPython.cpp

#include "fromPython.h"

int fromPython( boost::python::object &frame )
{
     cv::Mat image;
     // this is the function from modules/python/src2/cv2.cpp (the third parameter might be ArgInfo in later OpenCV versions)
     pyopencv_to( frame.ptr( ), image, "info", true );

     ///
     ///  HERE code using cv::Mat image          
     ///

     return 1;
} 
#include "fromPython.h"
using namespace boost::python; 

/// This function needs to be included to pass PyObjects as numpy array ( http://mail.python.org/pipermail/cplusplus-sig/2006-September/011021.html )
void* extract_pyarray( PyObject* x )
{
    return PyObject_TypeCheck( x, &PyArray_Type ) ? x : 0;
}

BOOST_PYTHON_MODULE( myWrapper )
{
     // This function needs to be included to pass PyObjects as numpy array ( http://mail.python.org/pipermail/cplusplus-sig/2006-September/011021.html )
     boost::python::converter::registry::insert( &extract_pyarray, type_id<PyArrayObject>( ) ); 
     def fromPython( "fromPython", &fromPython );
} 
import myWrapper
import cv2 

def myFunct():
    cap = cv2.VideoCapture(0)
    while(1):
        ret,frame = cap.read()
        myWrapper.fromPython(frame)
Call Python Function with Opencv in Django

Call Python Function with Opencv in Django


By : Dan
Date : March 29 2020, 07:55 AM
I wish did fix the issue. The easiest way to call a python function is in your view, not your template. You could do something like:
code :
def my_view(request):
    image_url = get_face_recog(path, image_path)
    return render(request, 'mytemplate.html', {'image_url': image_url})
<img src="{{ MEDIA_URL }}{{ image_url }}" />
How to create Trackbars which do not call any function? OpenCV 3.1 with Python 2.7

How to create Trackbars which do not call any function? OpenCV 3.1 with Python 2.7


By : Prem
Date : March 29 2020, 07:55 AM
hope this fix your issue Why not just create a simple function as expected?
Simple solution is to define a trivial function that returns the trackbar position. It will be called as the trackbar is moved by the user, but nothing will happen.
code :
import cv2
def f(x): return x
win = cv2.namedWindow("MyImage")
tb = cv2.createTrackbar("MyTrackbar","MyImage",0,179,f)
#assume you have some cv2 image already loaded
cv2.imshow("MyImage", img)
import cv2
win = cv2.namedWindow("MyImage")
tb = cv2.createTrackbar("MyTrackbar","MyImage",0,179,lambda x:x)
#assume you have some cv2 image already loaded
cv2.imshow("MyImage", img)
What is the correct way to call this OpenCV function from Python?

What is the correct way to call this OpenCV function from Python?


By : James Chu
Date : March 29 2020, 07:55 AM
I hope this helps . Apparently, the version of OpenCV 3.2.0 that I compiled for Python was missing this fix locally. I went ahead and recompiled my python bindings using the latest stable release of OpenCV 3.3.0 and the latest changes to the OpenCV contrib repository and the sample script worked as expected after that.
Related Posts Related Posts :
  • unable to post file+data using python-requests
  • How to test aws lambda functions locally
  • inconsistent plot between matplotlib and seaborn in Python
  • How matplotlib show obvious changes?
  • Project in Python3, reading files, word data
  • Check for specific Item in list without Iteration or find()
  • Unicode encoding when reading from text file
  • Overloaded variables in python for loops?
  • All elements have same value after appending new element
  • Python Threading loop
  • `_pickle.UnpicklingError: the STRING opcode argument must be quoted`
  • Python: How to stop a variable from exceeding a value?
  • python textblob and text classification
  • Django - Context dictionary for attribute inside a class
  • Database is not updated in Celery task with Flask and SQLAlchemy
  • Shapely intersections vs shapely relationships - inexact?
  • How to extract a percentage column from a periodic column and the sum of the column?
  • Zombie ssh process using python subprocess.Popen
  • Python regex to capture a comma-delimited list of items
  • joining string and long in python
  • Value Error in python numpy
  • Check if any character of a string is uppercase Python
  • TensorFlow - why doesn't this sofmax regression learn anything?
  • Python Anaconda Proxy Setup via .condarc file on Windows
  • Creating django objects from emails
  • Get spotify currently playing track
  • Select multiple columns and remove values according to a list
  • Python - How to Subtract a Variable By 1 Every Second?
  • Tkinter unable to alloc 71867 bytes
  • How to add Variable to JSON Python Django
  • CSRF token missing or invalid Django
  • Python: writing to a text file
  • Extracting multiple rows from pandas dataframe and converting to columns
  • Pinging a remote PC with Flask, causing server to block
  • Making a fractal graph using a 2D array?
  • Replacing a word in a list with a value from a dict
  • Savefig as eps yields a non-usable eps
  • Crispy-forms InlineRadios don't show my model state
  • Getting Title of a text
  • Python with numpy: How to delete an element from each row of a 2-D array according to a specific index
  • Sending and Receive data from a web page - Selenium
  • KeyError with Pyro4
  • Python module error
  • Python :: Attribute in superclass not available in inheriting subclass
  • Why does greater than and unequal operators work even though only less than and equal operator has been overloaded
  • Input length mismatch scikit
  • Print String in decreasing length
  • Overloading the [] operator in python class to refer to a numpy.array data member
  • Sympy - altering the range of the y axis for a plot
  • How do I programmatically list a DLL's dependencies in C++ or Python?
  • How do I lock window resizing in a Python matplotlib window?
  • Word boundary RegEx search using PyMongo
  • Iterating over a string by only changing one element in the string
  • classification of data where attribute values are strings
  • Validate user input using regular expressions
  • Synchronizing and Resampling two timeseries with non-uniform millisecond intraday data
  • determing the number of sentences, words and letters in a text file
  • Deploying impure Python packages to AWS
  • Navigating between multiple Tkinter GUI frames
  • Python - Do I need to remove instances from a dictionary?
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co