import cv2
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
cv2.calHist(imgs, channel, mask, nbins, ranges)
imread(path, cv2.IMREAD_GRAYSCALE)
is very different from loading the color image, and then cv2.cvtColor
, and generally we should stick with the second method like all the time (otherwise the histogram is wreid)beach = cv2.imread("data/images/beach.png")[:,:,::-1]
beach_gray = cv2.imread("data/images/beach.png", cv2.IMREAD_GRAYSCALE)
#cv2.cvtColor(beach, cv2.COLOR_RGB2GRAY)
plt.imshow(beach)
plt.figure()
plt.imshow(beach_gray, cmap = plt.cm.gray)
plt.figure()
plt.imshow(cv2.cvtColor(beach[:,:,::-1], cv2.COLOR_BGR2GRAY), cmap = plt.cm.gray)
<matplotlib.image.AxesImage at 0x7f323df70590>
np.all(beach_gray == cv2.cvtColor(beach[:,:,::-1], cv2.COLOR_BGR2GRAY))
False
np.all(beach_gray == cv2.cvtColor(beach, cv2.COLOR_RGB2GRAY))
False
np.all(cv2.cvtColor(beach[:,:,::-1], cv2.COLOR_BGR2GRAY)
== cv2.cvtColor(beach, cv2.COLOR_RGB2GRAY))
True
beach_gray = cv2.cvtColor(beach, cv2.COLOR_RGB2GRAY)
## gray scale hist
gray_hist = cv2.calcHist([beach_gray], [0], mask = None, histSize = [256], ranges = [0, 256])
plt.plot(gray_hist)
plt.xlim([0, 256])
print gray_hist.shape
(256, 1)
gray_hist = cv2.calcHist(beach_gray, [0], mask = None, histSize = [256], ranges = [0, 256])
plt.plot(gray_hist)
plt.xlim([0, 256])
plt.title("Wrong Histogram")
print gray_hist.shape
(256, 1)
gray_histm, _ = np.histogram(beach_gray.ravel(), bins = 250, )
plt.plot(gray_histm)
[<matplotlib.lines.Line2D at 0x7f323df269d0>]
_ = plt.hist(beach_gray.ravel(), bins = 255)
color histogram INDEPENDENTLY
for i, col in enumerate(["red", "green", "blue"]):
col_img = beach[:, :, i]
col_hist = cv2.calcHist([col_img], [0], mask = None,
histSize = [256], ranges = [0, 256])
plt.plot(col_hist, color = col, label = col)
plt.xlim([0, 256])
plt.legend()
<matplotlib.legend.Legend at 0x7f324c0cc1d0>
two peaks in blue are probably sea and sky. the peak in green are leaves, whereas the peak in red are from the yellow trucks or rocks
color histogram COMBINATORIALLY
r, g, b = cv2.split(beach)
channels = {"red": r, "green": g, "blue": b}
import itertools
for c1, c2 in list(itertools.combinations(channels, 2)):
rg_hist = cv2.calcHist([channels[c1], channels[c2]], [0, 1],
None, [32, 32], [0, 256, 0, 256])
plt.figure()
plt.matshow(rg_hist)
plt.colorbar()
plt.title("joint histogram of %s and %s" % (c1, c2))
<matplotlib.figure.Figure at 0x7f324c2b6210>
<matplotlib.figure.Figure at 0x7f324c057050>
<matplotlib.figure.Figure at 0x7f324c0727d0>
fig, axes = plt.subplots(2, 2, figsize = (2 * 6, 2 * 6))
equalized_gray = cv2.equalizeHist(beach_gray, )
axes[0, 0].imshow(beach_gray, cmap = plt.cm.gray)
axes[0, 1].imshow(equalized_gray, cmap = plt.cm.gray)
axes[1, 0].plot(cv2.calcHist([beach_gray], [0], None, [256], [0, 256], ))
axes[1, 1].plot(cv2.calcHist([equalized_gray], [0], None, [256], [0, 256], ))
[<matplotlib.lines.Line2D at 0x7f323ccb5c50>]