当前位置:网站首页>Basic operation of color histogram

Basic operation of color histogram

2022-07-08 02:20:00 So come on

1 Histogram is the intensity distribution of pixels in the image .

2 The histogram counts the number of pixels of each intensity value .

3cv2.calcHist(images, channels, mask, histSize, ranges)

# 1  Import library 
import cv2
import matplotlib.pyplot as plt
import numpy as np

# 2  Method : display picture 
def show_image(image, title, pos):
    plt.subplot(3, 2, pos)
    plt.title(title)
    image_RGB = image[:, :, ::-1] # BGR to RGB
    plt.imshow(image_RGB)
    plt.axis("off")  #  Axis closed 

# 3  Method : Display color histogram  b, g, r
def show_histogram(hist, title, pos, color):
    plt.subplot(3, 2, pos)
    plt.title(title)
    plt.xlim([0, 256])
    for h, c in zip(hist, color): # color: ('b', 'g', 'r')   Tuples 
        plt.plot(h, color=c)


# 4  Method : Calculate the histogram 
def calc_color_hist(image): #  A picture came in 
    # b, g, r
    hist = [] # An empty list , Step by step 
    hist.append( cv2.calcHist([image], [0], None, [256], [0, 256]))
    hist.append( cv2.calcHist([image], [1], None, [256], [0, 256]))
    hist.append( cv2.calcHist([image], [2], None, [256], [0, 256]))
    return hist

# 5  The main function 
def main():
    # 5.1  Create a canvas 
    plt.figure(figsize=(12, 8))
    plt.suptitle("Color Histogram", fontsize=10, fontweight="bold")

    # 5.2  Read original picture 
    img = cv2.imread("children.jpg")

    # 5.3  Calculate the histogram 
    img_hist = calc_color_hist(img)

    # 5.4  Display pictures and histograms 
    show_image(img, "RGB Image", 1)
    show_histogram(img_hist, "RGB Image Hist", 2, ('b', 'g', 'r'))  #  Pass a tuple bgr, No m

    # 5.5  Each pixel in the original picture increases 50 Pixel values 
    M = np.ones(img.shape, dtype="uint8") * 50

    added_image = cv2.add(img, M) #  Pixels are added one by one 
    added_image_hist = calc_color_hist(added_image)
    show_image(added_image, 'added image', 3)
    show_histogram(added_image_hist, 'added image hist', 4, ('b', 'g', 'r'))


    # 5.6  Subtract... From each pixel in the original picture 50 Pixel values 
    subtracted_image = cv2.subtract(img, M)
    subtracted_image_hist = calc_color_hist(subtracted_image)
    show_image(subtracted_image, 'subtracted image', 5)
    show_histogram(subtracted_image_hist, 'subtracted image hist', 6, ('b', 'g', 'r'))

    plt.show()
if __name__ == '__main__':
    main()
原网站

版权声明
本文为[So come on]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130539412366.html