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
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)
I have build some code in python from that code. However, the results are not the same
again, the c++ code is already wrong and broken.
never write for-loops like that, please.