Image Histogram
"An image histogram is a type of histogram that acts as a graphical representation of the tonal distribution in a digital image. It plots the number of pixels for each tonal value. By looking at the histogram for a specific image a viewer will be able to judge the entire tonal distribution at a glance." - Image histogram.
- Histogram is a graphical representation of the intensity distribution of an image.
- Histogram quantifies the number of pixels for each intensity value.
Here is a simple code for just loading the image:
import cv2 import numpy as np gray_img = cv2.imread('images/SunsetGoldenGate.jpg', cv2.IMREAD_GRAYSCALE) cv2.imshow('GoldenGate',gray_img) while True: k = cv2.waitKey(0) & 0xFF if k == 27: break # ESC key to exit cv2.destroyAllWindows()
GGsunset.png
Histo_gray.png
The code for histogram looks like this:
import cv2 import numpy as np from matplotlib import pyplot as plt gray_img = cv2.imread('images/GoldenGateSunset.png', cv2.IMREAD_GRAYSCALE) cv2.imshow('GoldenGate',gray_img) hist = cv2.calcHist([gray_img],[0],None,[256],[0,256]) plt.hist(gray_img.ravel(),256,[0,256]) plt.title('Histogram for gray scale picture') plt.show() while True: k = cv2.waitKey(0) & 0xFF if k == 27: break # ESC key to exit cv2.destroyAllWindows()
Note: This is how ravel() works, and it's equivalent of reshape(-1).
>>> x = np.array([[1, 2, 3], [4, 5, 6]]) >>> print np.ravel(x) [1 2 3 4 5 6] >>> x.reshape(-1) array([1, 2, 3, 4, 5, 6])
Before using that function, we need to understand some terminologies related with histograms.
- bins :The histogram above shows the number of pixels for every pixel value, from 0 to 255. In fact, we used 256 values (bins) to show the above histogram. It could be 8, 16, 32 etc. OpenCV uses histSize to refer to bins.
- dims : It is the number of parameters for which we collect the data. In our case, we collect data based on intensity value. So, in our case, it is 1.
- range : It is the range of intensity values we want to measure. Normally, it is [0,256], ie all intensity values.
OpenCV comes with an in-built cv2.calcHist() function for histogram. So, it's time to look into the specific parameters related to the cv2.calcHist() function.
cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])
In the code, we used:
hist = cv2.calcHist([gray_img],[0],None,[256],[0,256])
The parameters are:
- images: source image of type uint8 or float32. it should be given in as a list, ie, [gray_img].
- channels: it is also given in as a list []. It the index of channel for which we calculate histogram. For example, if input is grayscale image, its value is [0]. For color image, you can pass [0],[1] or [2] to calculate histogram of blue,green or red channel, respectively.
- mask: mask image. To find histogram of full image, it is set as None. However, if we want to get histogram of specific region of image, we should create a mask image for that and give it as mask.
- histSize: this represents our BIN count. Need to be given in []. For full scale, we pass [256].
- ranges: Normally, it is [0,256].
NumPy also provides us a function for histogram, np.histogram(). So, we can use NumPy fucntion instead of OpenCV function:
import cv2 import numpy as np from matplotlib import pyplot as plt gray_img = cv2.imread('images/GoldenGateSunset.png', cv2.IMREAD_GRAYSCALE) cv2.imshow('GoldenGate',gray_img) #hist = cv2.calcHist([gray_img],[0],None,[256],[0,256]) hist,bins = np.histogram(gray_img,256,[0,256]) plt.hist(gray_img.ravel(),256,[0,256]) plt.title('Histogram for gray scale picture') plt.show() while True: k = cv2.waitKey(0) & 0xFF if k == 27: break # ESC key to exit cv2.destroyAllWindows()
Other parts of the code remain untouched, and it gives us the same histogram.
Let's draw RGB histogram:
GoldenGateSunsetCV.png
Color_HIstogram.png
The code:
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('images/GoldenGateSunset.png', -1) cv2.imshow('GoldenGate',img) color = ('b','g','r') for channel,col in enumerate(color): histr = cv2.calcHist([img],[channel],None,[256],[0,256]) plt.plot(histr,color = col) plt.xlim([0,256]) plt.title('Histogram for color scale picture') plt.show() while True: k = cv2.waitKey(0) & 0xFF if k == 27: break # ESC key to exit cv2.destroyAllWindows()
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization
OpenCV 3 image and video processing with Python
OpenCV 3 with Python
Image - OpenCV BGR : Matplotlib RGB
Basic image operations - pixel access
iPython - Signal Processing with NumPy
Signal Processing with NumPy I - FFT and DFT for sine, square waves, unitpulse, and random signal
Signal Processing with NumPy II - Image Fourier Transform : FFT & DFT
Inverse Fourier Transform of an Image with low pass filter: cv2.idft()
Image Histogram
Video Capture and Switching colorspaces - RGB / HSV
Adaptive Thresholding - Otsu's clustering-based image thresholding
Edge Detection - Sobel and Laplacian Kernels
Canny Edge Detection
Hough Transform - Circles
Watershed Algorithm : Marker-based Segmentation I
Watershed Algorithm : Marker-based Segmentation II
Image noise reduction : Non-local Means denoising algorithm
Image object detection : Face detection using Haar Cascade Classifiers
Image segmentation - Foreground extraction Grabcut algorithm based on graph cuts
Image Reconstruction - Inpainting (Interpolation) - Fast Marching Methods
Video : Mean shift object tracking
Machine Learning : Clustering - K-Means clustering I
Machine Learning : Clustering - K-Means clustering II
Machine Learning : Classification - k-nearest neighbors (k-NN) algorithm
Python tutorial
Python Home
Introduction
Running Python Programs (os, sys, import)
Modules and IDLE (Import, Reload, exec)
Object Types - Numbers, Strings, and None
Strings - Escape Sequence, Raw String, and Slicing
Strings - Methods
Formatting Strings - expressions and method calls
Files and os.path
Traversing directories recursively
Subprocess Module
Regular Expressions with Python
Regular Expressions Cheat Sheet
Object Types - Lists
Object Types - Dictionaries and Tuples
Functions def, *args, **kargs
Functions lambda
Built-in Functions
map, filter, and reduce
Decorators
List Comprehension
Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism
Hashing (Hash tables and hashlib)
Dictionary Comprehension with zip
The yield keyword
Generator Functions and Expressions
generator.send() method
Iterators
Classes and Instances (__init__, __call__, etc.)
if__name__ == '__main__'
argparse
Exceptions
@static method vs class method
Private attributes and private methods
bits, bytes, bitstring, and constBitStream
json.dump(s) and json.load(s)
Python Object Serialization - pickle and json
Python Object Serialization - yaml and json
Priority queue and heap queue data structure
Graph data structure
Dijkstra's shortest path algorithm
Prim's spanning tree algorithm
Closure
Functional programming in Python
Remote running a local file using ssh
SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table
SQLite 3 - B. Selecting, updating and deleting data
MongoDB with PyMongo I - Installing MongoDB ...
Python HTTP Web Services - urllib, httplib2
Web scraping with Selenium for checking domain availability
REST API : Http Requests for Humans with Flask
Blog app with Tornado
Multithreading ...
Python Network Programming I - Basic Server / Client : A Basics
Python Network Programming I - Basic Server / Client : B File Transfer
Python Network Programming II - Chat Server / Client
Python Network Programming III - Echo Server using socketserver network framework
Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn
Python Coding Questions I
Python Coding Questions II
Python Coding Questions III
Python Coding Questions IV
Python Coding Questions V
Python Coding Questions VI
Python Coding Questions VII
Python Coding Questions VIII
Python Coding Questions IX
Python Coding Questions X
Image processing with Python image library Pillow
Python and C++ with SIP
PyDev with Eclipse
Matplotlib
Redis with Python
NumPy array basics A
NumPy Matrix and Linear Algebra
Pandas with NumPy and Matplotlib
Celluar Automata
Batch gradient descent algorithm
Longest Common Substring Algorithm
Python Unit Test - TDD using unittest.TestCase class
Simple tool - Google page ranking by keywords
Google App Hello World
Google App webapp2 and WSGI
Uploading Google App Hello World
Python 2 vs Python 3
virtualenv and virtualenvwrapper
Uploading a big file to AWS S3 using boto module
Scheduled stopping and starting an AWS instance
Cloudera CDH5 - Scheduled stopping and starting services
Removing Cloud Files - Rackspace API with curl and subprocess
Checking if a process is running/hanging and stop/run a scheduled task on Windows
Apache Spark 1.3 with PySpark (Spark Python API) Shell
Apache Spark 1.2 Streaming
bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...
Flask app with Apache WSGI on Ubuntu14/CentOS7 ...
Selenium WebDriver
Fabric - streamlining the use of SSH for application deployment
Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App
Neural Networks with backpropagation for XOR using one hidden layer
NLP - NLTK (Natural Language Toolkit) ...
RabbitMQ(Message broker server) and Celery(Task queue) ...
OpenCV3 and Matplotlib ...
Simple tool - Concatenating slides using FFmpeg ...
iPython - Signal Processing with NumPy
iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github
iPython and Jupyter Notebook with Embedded D3.js
Downloading YouTube videos using youtube-dl embedded with Python
Machine Learning : scikit-learn ...
Django 1.6/1.8 Web Framework ...