Friday 27 October 2017

Equalization of Histogram of an Image with & without OpenCV using C++

Code




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

using namespace std;
using namespace cv;

vector<int> histcal(const Mat image) {
  vector<int> arr(256, 0);
  for (int y = 0; y <= image.rows; y++)
    for (int x = 0; x <= image.cols; x++)
      arr[(int)(image.at<uchar>(y, x))]++;
  return arr;
}

void showhist(vector<int> arr, string name) {
  int maxi = 0;
  for (int i = 0; i < 256; i++)
    maxi = max(maxi, arr[i]);

  float factor = 400 / (float)maxi;
  Mat image = imread("contrast.jpg", CV_LOAD_IMAGE_GRAYSCALE);
  Mat himage = Mat::zeros(500, 400, image.type());
  Scalar col = Scalar(255, 255, 255);
  for (int i = 0; i < 256; i++) {
    int xshift = 50;
    int yfp = 450;  // first point
    int ysp = 450 - factor * arr[i];
    line(himage, Point(xshift + i, yfp), Point(xshift + i, ysp), col);
  }
  namedWindow(name.c_str(), WINDOW_NORMAL);
  imshow(name.c_str(), himage);
}

vector<int> mapping(vector<int> arr) {
  vector<int> carr(arr);
  for (int i = 1; i < 256; i++)
    carr[i] += carr[i - 1];
  vector<int> marr(256, 0);
  for (int i = 0; i < 256; i++) {
    marr[i] = (float(carr[i]) / carr[255] * 255) + 0.5;
  }

  return marr;
}

vector<int> eqhist(const vector<int> arr) {
  vector<int> marr = mapping(arr);
  vector<int> t(256, 0);
  for (int i = 0; i < 256; i++)
    t[marr[i]] += arr[i];
  return t;
}

Mat pixelmapper(const Mat img, vector<int> mapi) {
  Mat nimage = Mat(img.rows, img.cols, img.type());
  for (int y = 0; y < img.rows; y++)
    for (int x = 0; x < img.cols; x++)
      nimage.at<uchar>(y, x) = saturate_cast<uchar>(mapi[img.at<uchar>(y, x)]);
  return nimage;
}

int main() {
  // My cpp code
  Mat gimage;  // original image in grey
  gimage = imread("contrast.jpg", CV_LOAD_IMAGE_GRAYSCALE);
  vector<int> h = histcal(gimage);
  vector<int> e = eqhist(h);
  Mat nimage = pixelmapper(gimage, mapping(h));

  // Opencv Function used
  Mat eimage;
  equalizeHist(gimage, eimage);
  vector<int> ho = histcal(eimage);

  namedWindow("gimage", WINDOW_NORMAL);
  imshow("gimage", gimage);
  namedWindow("eqimage", WINDOW_NORMAL);
  imshow("eqimage", nimage);

  showhist(h, "original_histogram");
  showhist(e, "equalized_histogram");

  namedWindow("eqimageopencv", WINDOW_NORMAL);
  imshow("eqimageopencv", eimage);
  showhist(ho, "opencvhist");

  waitKey(0);
  return 0;
}

Compile & Run

[duke@duke-pc b9]$ g++ b9.cpp `pkg-config --cflags --libs opencv`
[duke@duke-pc b9]$ ./a.out

1 comment:


  1. I appreciate this piece of useful information. Kshemkari Export Import academy one of the best leading Trade and Training Institute for import and export business, provides the best service in India with expert TeamFor more information visit our site: Export Import Certificate Online Training

    ReplyDelete