颜色直方图比较简单,统计图像中的颜色分布。是个常用的全局特征,一般需要的话,可以加上SPM,能有效对空间位置进行编码。
代码如下:
- #include <sys/types.h>
- #include <boost/filesystem.hpp>
- #include "opencv2/core/core.hpp"
- #include "opencv2/highgui/highgui.hpp"
- #include "opencv2/nonfree/features2d.hpp"
- #include "opencv2/imgproc/imgproc.hpp"
- #include <boost/algorithm/string.hpp>
- using namespace cv;
- using namespace std;
- void compute_colorfeatures(const string& imgPath, vector<float>& features) {
- Mat mat = imread(imgPath);
- Mat hsv_img;
- cvtColor(mat, hsv_img, COLOR_BGR2HSV);
- int h_bins = 30;
- int s_bins = 50;
- int histSize[] = { h_bins, s_bins };
- // hue varies from 0 to 256, saturation from 0 to 180
- float s_ranges[] = { 0, 256 };
- float h_ranges[] = { 0, 180 };
- const float* ranges[] = { h_ranges, s_ranges };
- // Use the o-th and 1-st channels
- int channels[] = { 0, 1 };
- /// Histograms
- MatND color_features;
- /// Calculate the histograms for the HSV images
- calcHist(&hsv_img, 1, channels, Mat(), color_features, 2, histSize, ranges,
- true, false);
- normalize(color_features, color_features, 0, 1, NORM_MINMAX, -1, Mat());
- for (int i = 0; i < color_features.rows; i++) {
- for (int j = 0; j < color_features.cols; j++) {
- features.push_back(color_features.at<float>(i, j));
- }
- }
- }