Skip to content

Instantly share code, notes, and snippets.

@bikz05
Last active August 20, 2023 14:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bikz05/69375a01d422ec17e13b to your computer and use it in GitHub Desktop.
Save bikz05/69375a01d422ec17e13b to your computer and use it in GitHub Desktop.
This python script demonstrates how we can use a 3D histogram in OpenCV to sort the colors and find the max color in a image.
# This python script demonstrates how we can use a 3D
# histogram in OpenCV to sort the colors and find the
# max color in a image
import cv2
import numpy as np
# Read the image
image = cv2.imread("/home/bikz05/Desktop/dataset/0.png");
# Number of bins
LENGTH = 16
WIDTH = 16
HEIGHT = 16
bins = [LENGTH, WIDTH, HEIGHT];
# Range of bins
ranges = [0, 256, 0, 256, 0,256];
# Array of Image
images = [image];
# Number of channels
channels = [0, 1, 2];
#Calculate the Histogram
hist = cv2.calcHist(images, channels, None, bins, ranges);
# sortedIndex contains the indexes the
sortedIndex = np.argsort(hist.flatten());
# 1-D index of the max color in histogram
index = sortedIndex[-1]
# Getting the 3-D index from the 1-D index
k = index / (WIDTH * HEIGHT)
j = (index % (WIDTH * HEIGHT)) / WIDTH
i = index - j * WIDTH - k * WIDTH * HEIGHT
# Print the max RGB Value
print "Max RGB Value is = ", [i * 256 / HEIGHT, j * 256 / WIDTH, k * 256 / LENGTH]
@bikz05
Copy link
Author

bikz05 commented Dec 4, 2014

Histogram is a graphical representation that is used to represent the frequency of variables in the data. In this tutorial, we will discuss about how to generate a 3D histogram in OpenCV in Python and then we will use this histogram to find the color with the most number of pixels.

So, what we need to get a histogram in OpenCV?

In order to calculate the 3D histogram,

We need to specify the number of bins in each axis. The number of bins in each axis can be different, but in the tutorial we will set all of them equal to 16.
The next step is to specify the ranges of these bins. Again, we can select different ranges, but we will set the range from 0 to 256 for each axis. The value 256 is exclusive.
Next, we specify the number of channels whose histogram we want to calculate. In our case, its all three channels i.e [0, 1, 2]. If, it was a 2D array we might have had selected [0, 1] or [1, 2] or [0, 2] as per our choice.
Finally, is the set of images whose histogram we want to calculate and we, will set the mask to None.
Once, the histogram is calculated using calcHist(), we sort the indexes using np.argsort() in ascending order. Now, the last
value is the max color index. In the end, we multiply the index values by relevant constants to get the color in range [0,255].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment