005 OpenCV histogram

Table of contents

1. Environment

2. Overview of histogram principles

3. Code


1. Environment

The usage environment of this article is:

  • Windows10
  • Python 3.9.17
  • opencv-python 4.8.0.74

2. Overview of histogram principles

OpenCV is a widely used open source computer vision library that provides many functions and algorithms for image processing and analysis. Among them, histogram is a commonly used image analysis tool, which can be used to describe the distribution of pixel values ​​in an image. OpenCV provides a variety of histogram functions that can generate various types of histograms, including grayscale histograms, color histograms, integral histograms, etc.

A grayscale histogram is a histogram that describes the brightness distribution of an image. It shows how often each pixel value occurs, with the horizontal axis representing the pixel value and the vertical axis representing the frequency. The grayscale histogram can help us understand the brightness distribution of the image, such as whether the contrast and brightness of the image are appropriate, whether there are overexposure or underexposure, etc.

A color histogram is a histogram that describes the color distribution of an image. It shows the distribution of pixel values ​​for each color channel, with the horizontal axis representing the pixel value and the vertical axis representing the frequency. The color histogram can help us understand the color distribution of the image, such as whether the main color and color balance of the image are appropriate, whether there are color deviations and other issues.

The integral histogram is a function that extends the concept of histogram. It can not only describe the distribution of pixel values, but also the cumulative distribution of pixel values. The horizontal axis of the integral histogram represents the pixel value, and the vertical axis represents the sum of frequencies of all pixel values ​​below the pixel value. The integral histogram can help us understand the overall distribution of the image, such as whether the overall brightness distribution and color distribution of the image are appropriate.

The functions for generating histograms in OpenCV include improved versions of calcHist and and < a i=4>etc. Among them, the function can calculate one-dimensional or two-dimensional histograms, and can be applied to the histogram calculation of grayscale images or color images. The function can compare two histograms and is used to identify and compare histograms of different images. In addition, OpenCV also provides some other functions and algorithms, such as histogram equalization, histogram specification, etc., which can further expand the application scope of histograms. calcHistcalcHistcompareHistcalcHistcompareHist

Overall, OpenCV's histogram function is very powerful and flexible and can be applied to a variety of computer vision tasks. By using OpenCV's histogram functions and algorithms, we can better understand and analyze image data and improve the performance and accuracy of computer vision systems.

The simplest code:

from __future__ import print_function
import cv2 as cv
import argparse

parser = argparse.ArgumentParser(description='Code for Histogram Equalization tutorial.')
parser.add_argument('--input', help='Path to input image.', default='lena.jpg')
args = parser.parse_args()

src = cv.imread(cv.samples.findFile(args.input))
if src is None:
    print('Could not open or find the image:', args.input)
    exit(0)
src = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
dst = cv.equalizeHist(src)
cv.imshow('Source image', src)
cv.imshow('Equalized Image', dst)
cv.waitKey()

3. Code

OpenCV provides the function calcHist for calculating the histogram of a set of arrays (usually images or segmented channels). This function supports histograms up to 32 dimensions. When calling the calcHist function, you need to pass in some parameters, including:

  • images: input array, usually images;
  • channels: Specify the channel to calculate the histogram; if set to 0, it means calculating the histogram of all channels;
  • mask: mask image;
  • histSize: an integer or floating point number used to represent the size of the histogram; if set to an integer value (such as [16, 16]), the two values ​​represent the height and width of the histogram respectively. If it is a floating point value (such as [16.0, 16.0]), the two values ​​must be the same and represent the diameter of the histogram;
  • ranges: pixel value range;
  • hist: output array;
  • Accumulate: Boolean type, used to set whether to accumulate results into the output array.

Complete code:

from __future__ import print_function
from __future__ import division
import cv2 as cv
import numpy as np
import argparse

def Hist_and_Backproj(val):
    bins = val
    histSize = max(bins, 2)
    ranges = [0, 180]
    ## 获取直方图并归一化
    hist = cv.calcHist([hue], [0], None, [histSize], ranges, accumulate=False)
    cv.normalize(hist, hist, alpha=0, beta=255, norm_type=cv.NORM_MINMAX)
    backproj = cv.calcBackProject([hue], [0], hist, ranges, scale=1)
    cv.imshow('BackProj', backproj)
    w = 400
    h = 400
    bin_w = int(round(w / histSize))
    histImg = np.zeros((h, w, 3), dtype=np.uint8)
    for i in range(bins):
        cv.rectangle(histImg, (i*bin_w, h), ( (i+1)*bin_w, h - int(np.round( hist[i]*h/255.0 )) ), (0, 0, 255), cv.FILLED)
    cv.imshow('Histogram', histImg)

## 读取图片
parser = argparse.ArgumentParser(description='Code for Back Projection tutorial.')
parser.add_argument('--input', help='Path to input image.', default='data/home.jpg')
args = parser.parse_args()

src = cv.imread(cv.samples.findFile(args.input))
if src is None:
    print('Could not open or find the image:', args.input)
    exit(0)
## 彩色图转到HSV空间
hsv = cv.cvtColor(src, cv.COLOR_BGR2HSV)
ch = (0, 0)
hue = np.empty(hsv.shape, hsv.dtype)
# 由于ch=(0, 0),所有这里就是:将hsv的0通道复制到hue的0通道
cv.mixChannels([hsv], [hue], ch)
## 创建滑条
window_image = 'Source image'
cv.namedWindow(window_image)
bins = 25
cv.createTrackbar('* Hue  bins: ', window_image, bins, 180, Hist_and_Backproj )
Hist_and_Backproj(bins)
## 可视化
cv.imshow(window_image, src)
cv.waitKey()

Guess you like

Origin blog.csdn.net/m0_72734364/article/details/134512036