直方圖統計(map容器按值排序)
阿新 • • 發佈:2018-12-13
#include <iostream> #include<opencv.hpp> #include <vector> #include<map> #include<algorithm> using namespace std; using namespace cv; typedef pair<int, int> pii; bool comp(pii a, pii b){ return a.second > b.second; } void convertRGB2GRAY(const Mat&image, Mat&imageGray){ if (!image.data || image.channels() != 3) return; imageGray = Mat::zeros(image.size(), CV_8UC1); uchar*pointImage = image.data; uchar*pointImageGray = imageGray.data; int stepImage = image.step; int stepImageGray = imageGray.step; for (int i = 0; i < imageGray.rows; i++){ for (int j = 0; j < imageGray.cols; j++){ pointImageGray[i*stepImageGray + j] = 0.114*pointImage[i*stepImage + 3 * j] + 0.587*pointImage[i*stepImage + 3 * j + 1] + 0.299*pointImage[i*stepImage + 3 * j + 2]; } } } int main() { Mat image = imread("th.jpg"); namedWindow("w", CV_WINDOW_AUTOSIZE); imshow("w", image); Mat imageGray; convertRGB2GRAY(image, imageGray); namedWindow("g", CV_WINDOW_AUTOSIZE); imshow("g", imageGray); cout << "row:" << imageGray.rows << ",col:" << imageGray.cols << endl; map<int, int>m; for (int i = 0; i < imageGray.rows; i++){ for (int j = 0; j < imageGray.cols; j++){ m[imageGray.at<uchar>(i, j)]++; } } vector<pii>v(m.begin(),m.end()); sort(v.begin(), v.end(), comp); for (int i = 0; i < v.size(); i++){ cout << v[i].first << ":" << v[i].second << endl; } waitKey(0); return 0; }