Created
February 12, 2014 17:41
-
-
Save chewxy/8960637 to your computer and use it in GitHub Desktop.
Quick and Dirty Colour Histogram of a masked image in OpenCV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
import matplotlib.pyplot as plt | |
im = cv2.imread('IMG_3545S.JPG') | |
# convert to greyscale for easy thresholding | |
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) | |
# get a threshold - basically splits the image into black and white | |
thresh = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)[1] | |
# invert it. This is the mask we're gonna be using | |
invertMask = cv2.bitwise_not(thresh, thresh) | |
# calculate histograms! | |
histB = cv2.calcHist([im[...,0]], [0], invertMask, [256], [0,256]) # im[...,0] is the Blue channel | |
histG = cv2.calcHist([im[...,1]], [0], invertMask, [256], [0,256]) # im[...,1] is the Green channel | |
histR = cv2.calcHist([im[...,2]], [0], invertMask, [256], [0,256]) # im[...,2] is the Red channel | |
hist = cv2.calcHist([im], [0], invertMask, [256], [0,256]) # general histogram | |
#plot all the things! | |
fig = plt.figure() | |
plt.plot(histB, color='b') # plots histogram for the blue channel with a blue line | |
plt.plot(histG, color='g') | |
plt.plot(histR, color='r') | |
plt.plot(hist, color='k') # plots general histogram with a black line | |
plt.savefig('histogram.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment