使用Python的OpenCV直方图能否检测文本颜色和位置?

3

我需要在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()

图片背景透明

图片


一般情况下是不可能的。只有在特定情况下才有可能。您能否发布该图片?请尝试发布一个可执行的代码示例。 - Rotem
1
你的问题定义不太清楚。请澄清一下我们是否应该假设背景始终是白色的。同时,请澄清一下我们是否应该假设图像中除了文本以外没有其他对象/形状/图形。 - Mark Setchell
1个回答

3
在您发布的示例图像中,可以通过给定的直方图来近似计算文本的平均颜色。
在一般情况下,需要将文本与背景分离,并仅收集文本像素的直方图。
在您发布的图像中,我们可以假设背景是白色(RGB颜色约为[255, 255, 255]),而文本是暗色的(所有文本的RGB颜色分量值都很低)。
您可以使用以下步骤:
- 收集红、绿和蓝色通道的直方图。 - 从直方图中删除所有高值(将直方图值设置为零)。假设高值来自背景像素。 - 计算直方图的总和。总和表示原始图像中的像素数。 - 根据直方图计算原始图像中的像素总数。例如:如果`h[100]=10`,则图像中具有值为100的像素数为10。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循环。
我认为你最好修改代码,使用for循环。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接