Segmentation fault in pyopencv_from

asked 2014-10-27 10:37:23 -0500

Fe++ gravatar image

I am implementing a function in cpp that needs to convert a Mat to a PyObject for being passed to Python as a Numpy array. Thus, I am stuck with a segmentation fault error in the m.copyTo(temp) call inside the function pyopencv_from that do the job. Looks like the g_roicropping_numpyAllocator cannot do the job. Here I past the code:

static PyObject* pyopencv_from(const Mat& m)

{
    if( !m.data )
        Py_RETURN_NONE;
    Mat temp, *p = (Mat*)&m;
    if(!p->refcount || p->allocator != &g_roicropping_numpyAllocator)
    {

    temp.allocator = &g_roicropping_numpyAllocator;

    m.copyTo(temp);
    p = &temp;
}

p->addref();

return pyObjectFromRefcount(p->refcount);

}

ROICropping::ROICropping(){
    import_array(); // This is a function from NumPy that MUST be called.
}

PyObject* ROICropping::crop(PyObject* image, PyObject* labels, int label){



//Release GIL
    ScopedGILRelease scoped;

    cv::Mat cv_image;
    cv::Mat cv_labels;

    pyopencv_to(image, cv_image);
    pyopencv_to(labels, cv_labels);

    cv::Size s = cv_image.size();

    cv::Mat mask(s.height,s.width,CV_8UC1, cv::Scalar::all(0));

    assert(cv_labels.type() == CV_16SC1);
    assert(cv_image.type() == CV_8UC3 || cv_image.type() == CV_8UC1);

    uint8_t *image_data = (uint8_t*) cv_image.data;
    int16_t *labels_data = (int16_t*) cv_labels.data;
    uint8_t *mask_data = (uint8_t*) mask.data;

    int32_t x0=s.width, x1=0, y0=s.height, y1=0;

    int32_t tmp_val, idx;
    for(int j = 0; j < cv_labels.rows; j++){
        for(int i = 0; i < cv_labels.cols; i++){
            idx = cv_labels.cols * j + i;
            tmp_val = labels_data[ idx ];
            if(label==tmp_val){
                mask_data[ idx ] = 1;

                if(j<x0){
                    x0 = j;
                }
                if(j>x1){
                    x1 = j;
                }
                if(i<y0){
                    y0 = i;
                }
                if(i>y1){
                    y1 = i;
                }
            }
        }
    }

    cv::Rect roi(x0, y0, x1-x0+1, y1-y0+1);

    cv::Mat crop_image(y1-y0+1, x1-x0+1, CV_8UC1);
    cv::Mat image_roi = cv_image(roi);
    crop_image = image_roi.clone();

    cv::Mat crop_mask(y1-y0+1, x1-x0+1, CV_8UC1);
    cv::Mat mask_roi = mask(roi);
    crop_mask = mask_roi.clone();

    PyObject *py_crop_image = pyopencv_from(crop_image);
    PyObject *py_crop_mask = pyopencv_from(crop_mask);

    return Py_BuildValue("(NN)", py_crop_image, py_crop_mask);
}
edit retag flag offensive close merge delete