[PYTHON] How to get RGB and HSV histograms in OpenCV

Introduction

I am dealing with images and wanted to use the RGB and HSV histogram information as features. So I tried to extract the histogram using ** OpenCV **. I will leave it as a memo.

histogram

A histogram can be thought of as a graph or plot to know the overall distribution of pixel values in an image. Generally, the horizontal axis is the pixel value, and the vertical axis is the frequency of appearance of the pixel value. Histogram visualization is one way to understand an image.

What is the difference between RGB and HSV?

RGB

RGB is an acronym for red, green, and blue, respectively. These three colors are called the "three primary colors of light," and can be used on cathode ray tubes, liquid crystal monitors, etc. It is a method for expressing. Since 256 levels of darkness can be set for each primary color, 16,777,216 colors of 256 cubes can be expressed.

HSV

HSV is a method of expressing color with three elements: hue (Hue), saturation (Saturation), and brightness (Value / Brightness). ** Hue **: Hue ring (hue ring) The shape of the ring or displayed in the range of 0 to 360 degrees ** Saturation **: Degree of vividness of color: The lower the value, the lower the saturation, and the higher the value, the higher the saturation. ** Brightness **: Degree of brightness of color: When the value is low, it becomes dark, and when it is high, it becomes bright.

Loading images

Here are some points to note when loading images.

1. Loading with OpenvCV

import cv2

img = cv2.imread("sample.jpg ")

In this case, img is BGR. If you want to convert to RGB, you can convert it by the following method.

img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

2. Loading with pillow

from PIL import Image

img = Image.open("sample.jpg ")

When reading with pillow, you can read with RGB.

Function that returns RGB and HSV by specifying an image

I implemented a function that returns a histogram of R, G, B, H, S, V when an image is passed in Python. I also posted the result of executing with jupyter.


def show_img(path):

    img = cv2.imread(path)
    b, g, r = img[:,:,0], img[:,:,1], img[:,:,2]
    hist_b = cv2.calcHist([b],[0],None,[256],[0,256])
    hist_g = cv2.calcHist([g],[0],None,[256],[0,256])
    hist_r = cv2.calcHist([r],[0],None,[256],[0,256])
    plt.plot(hist_r, color='r', label="r")
    plt.plot(hist_g, color='g', label="g")
    plt.plot(hist_b, color='b', label="b")
    plt.legend()
    plt.show() 
    img2 = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    h, s, v = img2[:,:,0], img2[:,:,1], img2[:,:,2]
    hist_h = cv2.calcHist([h],[0],None,[256],[0,256])
    hist_s = cv2.calcHist([s],[0],None,[256],[0,256])
    hist_v = cv2.calcHist([v],[0],None,[256],[0,256])
    plt.plot(hist_h, color='r', label="h")
    plt.plot(hist_s, color='g', label="s")
    plt.plot(hist_v, color='b', label="v")
    plt.legend()
    plt.show()
    
    return hist_r,hist_g, hist_b, hist_h, hist_s, hist_v

This time I will try with the following dog image. dog.jpeg

r,g,b,h,s,v = show_img("dog.jpeg ")

Screenshot from 2020-01-20 08-45-48.png

About histogram calculation

OpenCV uses the following functions to calculate the histogram.

cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])

** images **: Input images. The pixel value data type is either uint8 or float32. Use the symbol [] to specify something like “[img]”. ** channels **: Index of the channel of the image for which the histogram is calculated. If the input image is a graceful image, specify [0]. For color images, specify one of the values [0], [1], and [2] that corresponds to the hues of B, G, and R for which the histogram is calculated. ** mask **: This is a mask image. Specify “None” to calculate the histogram of all pixels in the image. To calculate the histogram of a specific area in the image, specify a mask image that represents the specific area (an example is shown below). ** histSize **: The number of bins. This argument is also specified using the symbol []. Specify [256] if you want to target all pixel values. ** ranges **: RANGE that represents the range of pixel values for which you want to measure the histogram. Normally, specify [0,256].

References

-About RGB and CMYK in color

-What is HSV color space

-[Histogram # 1: Calculate, plot, and analyze !!!](http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc /py_histograms/py_histogram_begins/py_histogram_begins.html)

Recommended Posts

How to get RGB and HSV histograms in OpenCV
How to install OpenCV on Cloud9 and run it in Python
How to check opencv version in python
How to use is and == in Python
How to draw OpenCV images in Pygame
How to get a specific column name and index name in pandas DataFrame
How to get the date and time difference in seconds with python
How to generate permutations in Python and C ++
How to get results from id in Celery
How to get help in an interactive shell
How to get the files in the [Python] folder
How to write async and await in Vue.js
How to plot autocorrelation and partial autocorrelation in python
How to get the variable name itself in python
Allow Keras 2.0 and OpenCV 3.2 to work in GPU environment
How to get multiple model objects randomly in Django
How to define Decorator and Decomaker in one function
How to do zero-padding in one line with OpenCV
How to loop and play gif video with openCV
How to use Decorator in Django and how to make it
How to develop in Python
Convert RGB and HSV in a differentiable form with PyTorch
How to get rid of server custom emoji in message.content
[Go language] How to get terminal input in real time
How to swap elements in an array in Python, and how to reverse an array.
Foreigners talk: How to name classes and methods in English
How to use pyenv and pyenv-virtualenv in your own way
I tried "How to get a method decorated in Python"
How to create and use static / dynamic libraries in C
Comparison of how to use higher-order functions in Python 2 and 3
How to get a list of built-in exceptions in python
[Blender] How to handle mouse and keyboard events in Blender scripts
[TF] How to load / save Model and Parameter in Keras
Handling of HSV color space lower and upper in OpenCV
How to get an overview of your data in Pandas
How to execute external shell scripts and commands in python
How to create dataframes and mess with elements in pandas
[Shell] How to get the remote default branch in Git
How to get a quadratic array of squares in a spiral!
How to log in to AtCoder with Python and submit automatically
How to auto-update App Store description in Google Sheets and Fastlane
[Python] How to do PCA in Python
How to get and set the NTP server name by DHCP
How to compare lists and retrieve common elements in a list
How to install and use Tesseract-OCR
How to use classes in Theano
How to write soberly in pandas
How to get all the possible values in a regular expression
How to collect images in Python
Repeated @ app.callback in Dash How to write Input and State neatly
How to update Spyder in Anaconda
How to get followers and followers from python using the Mastodon API
How to use SQLite in Python
[Python] How to get the first and last days of the month
How to use functions in separate files Perl and Python versions
How to make a surveillance camera (Security Camera) with Opencv and Python
How to get a string from a command line argument in python
How to get the Python version
How to install OpenCV on Mac
How to convert 0.5 to 1056964608 in one shot
Difference in how to write if statement between ruby ​​and python