From a3d15a945594bf96b2cf229e453a827856ff892e Mon Sep 17 00:00:00 2001 From: bsdnoobz Date: Tue, 4 Dec 2012 20:34:26 +0700 Subject: Added display-histogram.cpp --- display-histogram.cpp | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 display-histogram.cpp diff --git a/display-histogram.cpp b/display-histogram.cpp new file mode 100644 index 0000000..6ebf93e --- /dev/null +++ b/display-histogram.cpp @@ -0,0 +1,74 @@ +#include +#include +#include + +using namespace cv; +using namespace std; + +void showHistogram(Mat& img) +{ + int bins = 256; // number of bins + int nc = img.channels(); // number of channels + vector hist(nc); + + for (int i = 0; i < hist.size(); i++) + hist[i] = Mat::zeros(1, bins, CV_32SC1); + + for (int i = 0; i < img.rows; i++) + { + for (int j = 0; j < img.cols; j++) + { + for (int k = 0; k < nc; k++) + { + uchar val = nc == 1 ? img.at(i,j) : img.at(i,j)[k]; + hist[k].at(val) += 1; + } + } + } + + int hmax[3] = {0,0,0}; + for (int i = 0; i < nc; i++) + { + for (int j = 0; j < bins-1; j++) + hmax[i] = hist[i].at(j) > hmax[i] ? hist[i].at(j) : hmax[i]; + } + + const char* wname[3] = { "blue", "green", "red" }; + Scalar colors[3] = { Scalar(255,0,0), Scalar(0,255,0), Scalar(0,0,255) }; + + vector canvas(nc); + + for (int i = 0; i < nc; i++) + { + canvas[i] = Mat::ones(125, bins, CV_8UC3); + + for (int j = 0, rows = canvas[i].rows; j < bins-1; j++) + { + line( + canvas[i], + Point(j, rows), + Point(j, rows - (hist[i].at(j) * rows/hmax[i])), + nc == 1 ? Scalar(200,200,200) : colors[i], + 1, 8, 0 + ); + } + + imshow(nc == 1 ? "value" : wname[i], canvas[i]); + } +} + +int main() +{ + Mat src = imread("c:/users/nash/desktop/assets/lena.jpg"); + + if (src.empty()) + return -1; + + showHistogram(src); + + imshow("src", src); + waitKey(0); + + return 0; +} + -- cgit v1.2.3