假设您对突出显示的区域有不同的颜色,而其余图像中不存在这种颜色 - 就像示例中突出显示的突出红色一样 - 您可以使用 HSV color space 合并 cv2.inRange 来使用颜色阈值.
因此,您需要为色调、饱和度和值设置适当的下限和上限。在给定的示例中,我们正在检测红色。所以,一般来说,我们需要两组限制,因为红色处于色调圆柱体的 0°/180°“转向”处。为了克服这一点,并且只使用一组限制,我们将获得的色调通道移动 90°,并取模 180°。此外,我们有高饱和度和相当明亮的红色,所以我们可能会看到饱和度水平高于 80%,价值水平高于 50%。我们得到这样一个面具:
最后要做的是从生成的掩码中获取轮廓,获取相应的边界矩形,然后在内容上运行pytesseract(灰度化,使用Otsu 进行阈值化以获得更好的OCR 性能)。我的建议是在这里也使用-psm 6 选项。
这是包含结果的完整代码:
import cv2
import numpy as np
import pytesseract
# Read image
img = cv2.imread('E5PY2.jpg')
# Convert to HSV color space, and split channels
h, s, v = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
# Shift hue channel to detect red area using only one range
h_2 = ((h.astype(int) + 90) % 180).astype(h.dtype)
# Mask highlighted boxes using color thresholding
lower = np.array([ 70, int(0.80 * 255), int(0.50 * 255)])
upper = np.array([110, int(1.00 * 255), int(1.00 * 255)])
highlighted = cv2.inRange(cv2.merge([h_2, s, v]), lower, upper)
# Find contours w.r.t. the OpenCV version; retrieve bounding rectangles
cnts = cv2.findContours(highlighted, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
rects = [cv2.boundingRect(cnt) for cnt in cnts]
# Iterate bounding boxes, and OCR
for x, y, w, h in rects:
# Grayscale, and threshold using Otsu
work = cv2.cvtColor(img[y:y+h, x:x+w], cv2.COLOR_BGR2GRAY)
work = cv2.threshold(work, 0, 255, cv2.THRESH_OTSU)[1]
# Pytesseract with -psm 6
text = pytesseract.image_to_string(work, config='--psm 6')\
.replace('\n', '').replace('\f', '')
print('X: {}, Y: {}, Text: {}'.format(x, y, text))
# X: 468, Y: 1574, Text: START MEDITATING
# X: 332, Y: 1230, Text: Well done. By signing up, you’ve taken your first
# X: 358, Y: 182, Text: Welcome
警告:我使用来自 Mannheim University Library 的特殊版本的 Tesseract。
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.19041-SP0
Python: 3.9.1
PyCharm: 2021.1.1
NumPy: 1.20.3
OpenCV: 4.5.2
pytesseract: 5.0.0-alpha.20201127
----------------------------------------