Beispiel #1
0
// Train svm on the count values in trainData and labels, then draw on
// image the classifications associated with each label value in green
// (+1.0) or blue (-1.0) according to what the resulting svm predicts.
//
static void drawSvmRegions(cv::Mat_<cv::Vec3b> &image, cv::SVM &svm,
                           int count, float trainData[][2], float labels[])
{
    static const cv::Mat zeroIdx;
    static const cv::Mat varIdx = zeroIdx;
    static const cv::Mat sampleIdx = zeroIdx;
    static const cv::SVMParams params = makeSvmParams();
    const cv::Mat labelsMat(count, 1, CV_32FC1, labels);
    const cv::Mat trainDataMat(count, 2, CV_32FC1, trainData);
    svm.train(trainDataMat, labelsMat, varIdx, sampleIdx, params);
    for (int i = 0; i < image.rows; ++i) {
        for (int j = 0; j < image.cols; ++j) {
            const cv::Mat sampleMat = (cv::Mat_<float>(1, 2) << i, j);
            const float response = svm.predict(sampleMat);
            if (response == 1.0) {
                image(j, i) = green;
            } else if (response == -1.0) {
                image(j, i) = blue;
            } else {
                std::cerr << "Unexpected response from SVM::predict(): "
                          << response << std::endl;
                assert(!"expected response from SVM");
            }
        }
    }
}
int TestMultiClassClassifier(const cv::SVM &SVM, const cv::Mat &data, const cv::Mat labels, FILE *report_file) {
	int confussion_matrix[ACTIONS_NUM][ACTIONS_NUM] = {0};
	float accuracy = 0.0f;

	for (int desc_idx = 0; desc_idx < data.rows; desc_idx++) {
		float label;
		int true_idx, predicted_idx;

		true_idx = (int)labels.at<float>(desc_idx);
		label = SVM.predict(data.row(desc_idx));		
		predicted_idx = (int)label;
		confussion_matrix[predicted_idx][true_idx]++;
		accuracy += (true_idx == predicted_idx)? 1: 0;
	}
	printf("============================================\n");
	fprintf(report_file, "============================================\n");
	
	accuracy /= data.rows;
	printf("accuracy: %2.2f\n", accuracy);
	fprintf(report_file, "accuracy: %2.2f\n", accuracy);

	for (int row = 0; row < ACTIONS_NUM; row++) {
		for (int col=0; col < ACTIONS_NUM; col++) {
			printf("%d\t\t",confussion_matrix[row][col]);
			fprintf(report_file,"%d\t\t",confussion_matrix[row][col]);
		}
		printf("\n");
		fprintf(report_file,"\n");
	}
	return 0;
}