Skip to content

Instantly share code, notes, and snippets.

@chewxy
Created February 12, 2014 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chewxy/8960637 to your computer and use it in GitHub Desktop.
Save chewxy/8960637 to your computer and use it in GitHub Desktop.
Quick and Dirty Colour Histogram of a masked image in OpenCV
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