Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Coverting C++ to Python

I have the following OpenCV code in c++ and I would like to convert it to python. Do any of you know how to convert those lines to python.

Mainly the Vec3f* and vector<mat> that are found at lines 13 and 31.

/**
* Create a sample vector out of RGB image
*/
Mat asSamplesVectors( Mat& img ) {
    Mat float_img;
    img.convertTo( float_img, CV_32F );

    Mat samples( img.rows * img.cols, 3, CV_32FC1 );

    /* Flatten  */
    int index = 0;
    for( int y = 0; y < img.rows; y++ ) {
        Vec3f * row = float_img.ptr(y);
        for( int x = 0; x < img.cols; x++ )
            samples.at<Vec3f>(index++, 0) = row[x];
        }
        return samples;
    }

/**
Perform segmentation (clustering) using EM algorithm
**/
vector EMSegmentation( Mat& image, int no_of_clusters = 2 ){
    Mat samples = asSamplesVectors( image );

    cout << "Starting EM training" << endl;
    EM em( no_of_clusters );
    em.train( samples );
    cout << "Finished training EM" << endl;

    vector<Mat> segmented;
    for( int i = 0; i < no_of_clusters; i++ )
        segmented.push_back( Mat::zeros( image.rows, image.cols, CV_8UC3 ) );

    int index = 0;
    for( int y = 0; y < image.rows; y++ ) {
        for( int x = 0; x < image.cols; x++ ) {
            int result = em.predict( samples.row(index++) )[1];
            segmented[result].at<Point3i>(y, x, 0) = image.at<Point3i>(y, x, 0);
        }
    }

    return segmented;
}

Thank you