OpenCV + python: Histogram application (a)

1, histogram equalization (Histogram Equalization)
if the gradation image is unevenly distributed, which intensity distribution concentrated in a narrow range, so that details of the image is not clear, the contrast is low. Histogram equalization, nonlinear stretching of the image, the gray value image redistribute the gray value image is within a certain range substantially equal. Thus, the original intermediate contrast histogram peak portion is enhanced, and the contrast of both sides of the bottom portion decreases, a histogram of the output image is relatively flat histogram. Range image gradation or gradation pulled evenly distributed, thereby increasing the contrast, so that a clear image detail, in order to achieve the purpose of enhanced.
Here Insert Picture Description

Equalization basic idea is: try such that each gray level equal to the number of pixels. Another advantage is that the histogram equalization: no additional parameters, the entire process is automated; histogram equalization is a disadvantage: after stretching some gray level may not be mapped to cause graininess in the image perception

Equalization algorithm

Histogram equalization is also an actual gradation conversion process, the current intensity distribution by a transform function, is converted into a wider range, more uniform distribution of gray scale images. I.e. the original image histogram modification is substantially uniformly distributed throughout the gray zone, thus enlarging the dynamic range of the image, image contrast enhancement. Typically equalization selected transform function is the cumulative probability gradation, histogram equalization step algorithm:
(1) Calculate the histogram of the original image P (Sk) = nk / n , where n is the total number of pixels, nk is Sk number of gray level pixels
(2) of the original image cumulative histogram is calculated the CDF (Sk) = Σni / = n-ΣPs (Si)
(. 3) L⋅CDF Dj = (Si), where Dj is the object image pixel, CDF (Si) is the source image gray level cumulative distribution i, L is the image the maximum gray level (255 grayscale)
specific code as follows:

void equalization_self(const Mat &src, Mat &dst)
{
    Histogram1D hist1D;
    MatND hist = hist1D.getHistogram(src);

    hist /= (src.rows * src.cols); // 对得到的灰度直方图进行归一化
    float cdf[256] = { 0 }; // 灰度的累积概率
    Mat lut(1, 256, CV_8U); // 灰度变换的查找表
    for (int i = 0; i < 256; i++)
    {
        // 计算灰度级的累积概率
        if (i == 0)
            cdf[i] = hist.at<float>(i);
        else
            cdf[i] = cdf[i - 1] + hist.at<float>(i);

        lut.at<uchar>(i) = static_cast<uchar>(255 * cdf[i]); // 创建灰度的查找表
    }

    LUT(src, lut, dst); // 应用查找表,进行灰度变化,得到均衡化后的图像

}

The above code simply to deepen the understanding of the process of the equalization algorithm, the actual OpenCV also provided in the gray scale equalization function.
Global histogram equalization source code example:

import cv2 as cv
import numpy as np


def equalHist_demo(image): #直方图均衡化,自动调整图像对比度,是图像增强的一种手段
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)#首先转化为灰度图
    dst = cv.equalizeHist(gray)
    cv.imshow("equalHist_demo", dst)
src = cv.imread("F:/images/rice.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
equalHist_demo(src)
cv.waitKey(0)

cv.destroyAllWindows()

The result:
Here Insert Picture DescriptionHere Insert Picture Descriptiona global histogram equalization improves contrast background. But lead to high brightness, we may lose most of the information. This is because it is not limited to a specific area of the histogram.
2, adaptive histogram equalization (Adaptive histgram equalization / AHE)

Adaptive histogram equalization (AHE) to a computer image processing technology to enhance the contrast of the image. And conventional histogram equalization algorithm different, AHE local histogram calculation algorithm of the image, and then redistributed to change the brightness of the image contrast. Thus, the algorithm is more suitable for local contrast to improve the image and to obtain more image detail.
The image is divided into small pieces referred to as "block" (in the in OpenCV, tileSize default to 8x8). Then, as usual, for each of these blocks histogram equalization. So in a small area, the histogram is restricted to a small area (unless there is noise). If there is noise, it will be magnified. To avoid this, the contrast limiting application. If any of the histogram bins above the specified contrast limit (default is 40 in OpenCV), before application of histogram equalization, to cut and evenly distributed pixels to other sections. After the equalizer, in order to remove the tile border flaws, bilinear interpolation.
ALGORITHM:
move the image on the template W A progressive movement, and the center of the template W c (x0, y0) corresponding to point f (x0, y0) on the image; calculating a template histogram equalization region W changes the relationship: g (x, y) = T ( f (x, y), calculates a template center point c (x0, y0) of the corresponding pixel values equalization:. g (x0, y0) = T (f (x0, y0)) using g (x0, y0) substitute f (x0, y0); progressive calculated adaptive histogram equalization of the entire image the image.

Is doing in a given histogram equalization box, and the box all processing (including equalization) only for the original pixel center point of a change to a new pixel b.
Code:

function [ output_img ] = my_AHE( input_img, w)
%UNTITLED Summary of this function goes here
%   Detailed explanation goes here
%   自适应直方图均衡化
%   输入:input_img:待处理图像
%        w: 局部处理的窗口大小
 
[height,width,channels]=size(input_img);
 
if channels==1
    src = inpit_img;
else
    src = rgb2gray(input_img);
end
 
%1.图像边界扩展
padsize=[(w-1)/2,(w-1)/2];
padSrc = padarray(src,padsize,'symmetric','both');
 
%2.循环求解每个区域对应的值
output_img = zeros(height,width);
iter = 0;
for i=1:height
    for j=1:width
        slideWindow = zeros(w,w);
        slideWindow = padSrc(i:i+w-1,j:j+w-1);
        AHE_piexl = my_AHE_piexl(slideWindow,src(i,j));
        output_img(i,j) = AHE_piexl;
        iter = iter+1;
        disp(iter);
    end
end
 
output_img = uint8(output_img);
 
 
end
 
function [ outPiexl ] = my_AHE_piexl( window,inPiexl )
%UNTITLED2 Summary of this function goes here
%   Detailed explanation goes here
%   计算局部图像的直方图均衡化的像素对应值
%   输入:window: 局部图像
%        inPiexl:输入像素
%        outPiexl:输出像素
 
[height,width]=size(window);
 
%1.像素灰度统计
NumPixel = zeros(1,256);
for i=1:height
    for j=1:width
        grayValue = window(i,j);
        NumPixel(1,grayValue+1) = NumPixel(1,grayValue+1)+1;
    end
end
 
%2.计算灰度分布密度
ProbPixel = zeros(1,256);  
for k=1:256
    ProbPixel(1,k)=NumPixel(1,k)/(height*width*1.0);
end
 
%3.计算累积分布密度
CumuPixel = zeros(1,256);  
CumuPixel(1,1) = ProbPixel(1,1);
for l=2:256
    CumuPixel(1,l) = CumuPixel(1,l-1)+ProbPixel(1,l);    
end
CumuPixel = uint8(255 .* CumuPixel + 0.5); %取整数
 
%4.计算灰度值映射
outPiexl = CumuPixel(inPiexl);
 
end

Similarly, the above code simply to deepen understanding of the flow equalization algorithm, actually OpenCV also provided a function of the gray balance.
Source Code Example:

import cv2 as cv
import numpy as np

def clahe_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    clahe = cv.createCLAHE(clipLimit=5.0, tileGridSize=(8, 8))
    dst = clahe.apply(gray)
    cv.imshow("clahe_demo", dst)


src = cv.imread("F:/images/rice.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
clahe_demo(src)

cv.waitKey(0)
cv.destroyAllWindows()

The result:
Here Insert Picture DescriptionHere Insert Picture Description3, histograms compare
the two images of the input histogram equalization and histogram calculation steps, can be compared to the histogram of the two images, and we want to get some conclusions by the results comparison.

Histogram Comparison

(1) image similarity comparison
if we have two images, and the same histogram of the two images, or very high similarity, so to a certain extent, we can say that these two figures are the same, this one of the applications is the histogram comparison.

(2) Analysis of the relationship between the image
histograms of the two images reflecting the distribution of the image pixels, an image histogram may be utilized to analyze the relationship between the two images.

Histogram comparison method

To compare two histograms (H1 and H2), we must first choose a standard measure of the histogram similarity comparison, we set d (H1, H2)
Here Insert Picture Description6.API introduced --compareHist

(1) step
. A first with cvtColor () converts an image from the RGB color space to HSV color space;
B image histogram is calculated and then normalized between [0 1], use the function calcHist (). and the normalize ();
. C is one of the above four methods are compared, the function used compareHist ().

(2) API Introduction

There are a function of three parameters, one input image, a picture, a method of comparing output. Case the value of the comparative method to the above four methods in OpenCV, each has its own name: Correlation (CV_COMP_CORREL); Chi- Square (CV_COMP_CHISQR); Intersection (CV_COMP_INTERSECT); Bhattacharyya distance (CV_COMP_BHATTACHARYYA).
Source Code Example:

import cv2 as cv
import numpy as np



def create_rgb_hist(image):
    h, w, c = image.shape
    rgbHist = np.zeros([16*16*16, 1], np.float32)   #需要是 np.float32类型
    bsize = 256 / 1
    for row in range(h):
        for col in range(w):
            b = image[row, col, 0]
            g = image[row, col, 1]
            r = image[row, col, 2]
            index = np.int(b/bsize)*16*16 + np.int(g/bsize)*16 + np.int(r/bsize)
            rgbHist[np.int(index), 0] = rgbHist[np.int(index), 0] + 1
    return rgbHist


def hist_compare(image1, image2):
    hist1 = create_rgb_hist(image1)
    hist2 = create_rgb_hist(image2)
    match1 = cv.compareHist(hist1, hist2, cv.HISTCMP_BHATTACHARYYA)#巴氏距离,越小越相似
    match2 = cv.compareHist(hist1, hist2, cv.HISTCMP_CORREL)#相关性,越大越相似
    match3 = cv.compareHist(hist1, hist2, cv.HISTCMP_CHISQR)#卡方,越小越相似
    print("巴氏距离: %s, 相关性: %s, 卡方: %s"%(match1, match2, match3))



image1 = cv.imread("F:/images/lena.png")
image2 = cv.imread("F:/images/lenanoise.png")
cv.imshow("image1", image1)
cv.imshow("image2", image2)
hist_compare(image1, image2)

cv.waitKey(0)

cv.destroyAllWindows()

The result:
Here Insert Picture DescriptionHere Insert Picture Description
Pap Distance: .09072200336618969, relevance: 0.9788106004024394, Chi-square: 164.3082768373199
above data shows two pictures are very similar. If the image size is inconsistent need to be normalized histogram.

Guess you like

Origin blog.csdn.net/qq_43660987/article/details/90947177