是否可以使用python中的opencv直方图检测文本颜色?

问题描述 投票:0回答:1

我需要在opencv中检测图像上文本的颜色,并使用直方图获得平均颜色。

可以这样做吗?

我现在有此代码:

color = ('b','g','r')
for i,col in enumerate(color):
    histr = cv2.calcHist([img],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])
plt.show()

îmage

python opencv text colors histogram
1个回答
0
投票

在您发布的示例图像中,可以通过给定的直方图来近似文本的平均颜色。

通常情况下,您需要将文本与背景分开,并仅收集文本像素的直方图。

在您发布的图像中,我们可以假定背景为白色(RGB颜色约为[255、255、255]),文本为深色(所有RGB文本的颜色分量值都很低)。

您可以使用以下阶段:

  • 收集红色,绿色和蓝色通道的直方图。
  • 从直方图中删除所有高值(将直方图值设置为零)。假设较高的值来自背景像素。
  • 计算直方图的总和。总和表示原始图像中的像素数。
  • 根据直方图计算原始图像中像素的总和。例:如果h[100] = 10然后,图像中有10个像素,其值为100。10个像素的总和为100 * 10。原始图像中像素的总和为:h[0]*0 + h[1]*1 + h[2]*2...
  • 计算平均值-将总数除以计数。

这里是代码:

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))

注意:我故意使代码简单,没有for循环。我认为您最好修改代码,并使用循环。

© www.soinside.com 2019 - 2024. All rights reserved.