Coverting C++ to Python

asked 2018-03-15 21:58:52 -0600

Tarcisioflima gravatar image

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

edit retag flag offensive close merge delete

Comments

that c++ code is already horrible, don't try to use that literally.

EM (like all opencv ml algorithms) expects each sample as a 1d float array on a row, but you could rather reshape() it from numpy, than do complicated copying like above

(numpy's reshape() works a bit different from opencv's so i can' quite answer)

berak gravatar imageberak ( 2018-03-16 01:57:28 -0600 )edit

I have build some code in python from that code. However, the results are not the same

Tarcisioflima gravatar imageTarcisioflima ( 2018-03-17 00:28:53 -0600 )edit

again, the c++ code is already wrong and broken.

 samples.at<Vec3f>(index++, 0)    <-- wrong type, samples is CV_32FC1
  segmented[result].at<Point3i>(y, x, 0)  <-- wrong, again, segmented is CV_8UC3 
 image.at<Point3i>(y, x, 0); <-- more of the same

never write for-loops like that, please.

berak gravatar imageberak ( 2018-03-17 02:24:06 -0600 )edit