Opencv 直方图归一化

来归一化直方图吧。

有时直方图会偏向一边。

比如说,数据集中在0处(左侧)的图像全体会偏暗,数据集中在255处(右侧)的图像会偏亮。

如果直方图有所偏向,那么其动态范围( dynamic range )就会较低。

为了使人能更清楚地看见图片,让直方图归一化、平坦化是十分必要的。

这种归一化直方图的操作被称作灰度变换(Grayscale Transformation)。像素点取值范围从[c,d]转换到[a,b]的过程由下式定义。这回我们将imori_dark.jpg的灰度扩展到[0, 255]范围:

Opencv 直方图归一化

python实现:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# histogram normalization
def hist_normalization(img, a=0, b=255):
    # get max and min
    c = img.min()
    d = img.max()

    out = img.copy()

    # normalization
    out = (b-a) / (d - c) * (out - c) + a
    out[out < a] = a
    out[out > b] = b
    out = out.astype(np.uint8)

    return out


# Read image
img = cv2.imread("imori_dark.jpg").astype(np.float)
H, W, C = img.shape

# histogram normalization
out = hist_normalization(img)

# Display histogram
plt.hist(out.ravel(), bins=255, rwidth=0.8, range=(0, 255))
plt.savefig("out_his.png")
plt.show()

# Save result
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.imwrite("out.jpg", out)

c++实现:

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <math.h>


// histogram normalization
cv::Mat histogram_normalization(cv::Mat img, int a, int b){
  // get height and width
  int width = img.cols;
  int height = img.rows;
  int channel = img.channels();

  int c, d;
  int val;

  // prepare output
  cv::Mat out = cv::Mat::zeros(height, width, CV_8UC3);

  // get [c, d]
  for (int y = 0; y < height; y++){
    for (int x = 0; x < width; x++){
      for (int _c = 0; _c < channel; _c++){
        val = (float)img.at<cv::Vec3b>(y, x)[_c];
        c = fmin(c, val);
        d = fmax(d, val);
      }
    }
  }

  // histogram transformation
  for (int y = 0; y < height; y++){
    for ( int x = 0; x < width; x++){
      for ( int _c = 0; _c < 3; _c++){
        val = img.at<cv::Vec3b>(y, x)[_c];

        if (val < a){
          out.at<cv::Vec3b>(y, x)[_c] = (uchar)a;
        }
        else if (val <= b){
          out.at<cv::Vec3b>(y, x)[_c] = (uchar)((b - a) / (d - c) * (val - c) + a);
        }
        else {
          out.at<cv::Vec3b>(y, x)[_c] = (uchar)b;
        }
      }
    }
  }

  return out;
}


int main(int argc, const char* argv[]){
  // read image
  cv::Mat img = cv::imread("imori_dark.jpg", cv::IMREAD_COLOR);

  // histogram normalization
  cv::Mat out = histogram_normalization(img, 0, 255);

  //cv::imwrite("out.jpg", out);
  cv::imshow("answer", out);
  cv::waitKey(0);
  cv::destroyAllWindows();

  return 0;
}

输入:

Opencv 直方图归一化

输出:

Opencv 直方图归一化

直方图:

Opencv 直方图归一化

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程