In the sample image you have posted it is possible to approximate the average color of the text by given histograms.
In the general case, you need to separate the text form the background, and collect histogram of text pixels only.
In the image you have posted, we can assume that the background is white (RGB color about [255, 255, 255]), and the text is dark (all RGB the color components values of the text are low).
You may use the following stages:
- Collect histograms of red, green and blue color channels.
- Remove all high values from histograms (set histogram value to zero).
Assume the high values are from background pixels.
- Compute the sum of the histograms.
Sum represents the count of pixels in the original image.
- Compute the sum of pixels in the original image according to histogram.
Example:
If h[100] = 10
Then there are 10 pixels with value 100 in the image.
The sum of the 10 pixels is 100*10.
The sum of an pixels in the original image is: h[0]*0 + h[1]*1 + h[2]*2...
- Compute the average - divide sum by count.
Here is the code:
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('img.png') # Read input image
h_red = cv2.calcHist([img], [2], None, [256], [0,256])
h_green = cv2.calcHist([img], [1], None, [256], [0,256])
h_blue = cv2.calcHist([img], [0], None, [256], [0,256])
#h_red.sum() must be img.shape[0]*img.shape[1]
# Remove background pixels from the histograms.
# Set histogram bins above 230 with zero
# assume all text has lower values of red, green and blue.
h_red[230:] = 0
h_green[230:] = 0
h_blue[230:] = 0
# Compute number of elements in histogram, after removing background
count_red = h_red.sum()
count_green = h_green.sum()
count_blue = h_blue.sum()
# Compute the sum of pixels in the original image according to histogram.
# Example:
# If h[100] = 10
# Then there are 10 pixels with value 100 in the image.
# The sum of the 10 pixels is 100*10.
# The sum of an pixels in the original image is: h[0]*0 + h[1]*1 + h[2]*2...
sum_red = np.sum(h_red * np.c_[0:256])
sum_green = np.sum(h_green * np.c_[0:256])
sum_blue = np.sum(h_blue * np.c_[0:256])
# Compute the average - divide sum by count.
avg_red = sum_red / count_red
avg_green = sum_green / count_green
avg_blue = sum_blue / count_blue
print('Text RGB average is about: {}, {}, {}'.format(avg_red, avg_green, avg_blue))
Note:
I deliberately kept the code simple, with no for loops.
I think you better modify the code, and use for loops.