cn_feature c++实现

cn特征 c++实现
vs2015

#include <iostream>
#include <opencv2/opencv.hpp>
#include <vector>

//#include <matio.h>
//
class cn_feature {
public:
	bool init(std::string cnfile);
	cv::Mat get_features(const cv::Mat& img);
private:
	std::string _cnfileName;
	cv::Mat w2c;
	bool data_is_true{ false };
};

bool cn_feature::init(std::string cnfile)
{
	FILE* fp;
	fopen_s(&fp, cnfile.c_str(), "r");

	char buffer[1024] = { 0 };

	std::vector<float> w2cdata;
	w2cdata.clear();

	while (!feof(fp)) {
		fgets(buffer, 512, fp);
		char* p[20];
		char* buf;
		p[0] = strtok_s(buffer, "\t", &buf);
		int i = 0;
		while (p[i]) {
			i++;
			p[i] = strtok_s(NULL, "\t", &buf);
		}
		p[i] = "\0";

		for (int i = 0; i < 10; i++) {
			//printf("p[%d] = %s\n", i, p[i]);
			w2cdata.push_back(atof(p[i]));
		}

	}
	fclose(fp);

	printf("size = %d\n", w2cdata.size());
	if (w2cdata.size() % 10 == 0) {
		data_is_true = true;
		w2c = cv::Mat(w2cdata, true);
		//printf("w2c size(%d, %d)\n", w2c.rows, w2c.cols);

		w2c = w2c.reshape(0, w2cdata.size() / 10);
		//w2c = w2c.reshape(0, w2c.rows*w2c.cols/10);
		return true;
	}
	return false;
}

cv::Mat cn_feature::get_features(const cv::Mat& img) {
	if (!data_is_true) {
		return cv::Mat::zeros(img.size(), img.type());
	}

	int area_lens = img.rows*img.cols;
	cv::Mat featureMap = cv::Mat::zeros(area_lens, w2c.cols, CV_32FC1);

	std::vector<cv::Mat> s;
	cv::split(img, s);//bgr

	int* index_im = new int[area_lens];
	memset(index_im, 0, area_lens*sizeof(int));

	unsigned char* r = s[2].data;
	unsigned char* g = s[1].data;
	unsigned char* b = s[0].data;

	for (int i = 0; i < area_lens; i++) {
		index_im[i] = 1 + floor(r[i] / 8) + 32 * floor(g[i] / 8) + 32 * 32 * floor(b[i]/8);
	}
	//cv::Mat index_im = 1 + s[2] / 8 + 32* s[1] / 8 + 32 * 32 * s[0] / 8;

	for (int i = 0; i < featureMap.rows; i++) {
		//获取行号
		int rows = index_im[i];
		//w2c的行指针
		float* ptr_rows = (float*)w2c.data + rows*w2c.cols;
		//feature的行指针
		float* ftr_rows = (float*)featureMap.data + i*featureMap.cols;
		for (int j = 0; j < featureMap.cols; j++) {
			ftr_rows[j] = ptr_rows[j];
		}
	}

	printf("cols = %d\n", w2c.cols);
	featureMap = featureMap.reshape(w2c.cols, img.rows);
	return featureMap;
}

int main(int argc, char** argv) {
	cv::Mat src = cv::imread("messi.jpg");
	cn_feature CN;
	CN.init("cn.txt");
	cv::Mat cn_feature = CN.get_features(src);

	std::vector<cv::Mat> cns;
	cv::split(cn_feature, cns);

	cv::imshow("cns0.jpg", cns[0]);
	cv::waitKey(0);

	system("pause");
	return 0;
}

posted @ 2021-01-18 20:52  快乐码小农  阅读(164)  评论(0编辑  收藏  举报