使用 python 突出显示图像中的特定文本

Highlighting specific text in an image using python

我想在网站截图中突出显示特定的 words/sentences。

截取屏幕截图后,我使用 pytesseractcv2 提取文本。这很好用,我可以获得有关它的文本和数据。

import pytesseract
import cv2


if __name__ == "__main__":
    img = cv2.imread('test.png')
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    result = pytesseract.image_to_data(img, lang='eng', nice=0, output_type=pytesseract.Output.DICT)
    print(result)

使用结果对象我可以找到需要的单词和句子。

问题是如何返回到图像并突出显示那些词?

我应该看看其他库还是有办法获取像素值然后突出显示文本?

理想情况下,我想获得每个单词的开始和结束坐标,该怎么做?

您可以使用pytesseract.image_to_boxes 方法获取图像中识别出的每个字符的边界框位置。如果需要,您还可以使用该方法在某些特定字符周围绘制边界框。下面的代码在我识别的图像周围绘制了矩形。

import cv2
import pytesseract
import matplotlib.pyplot as plt

filename = 'sf.png'

# read the image and get the dimensions
img = cv2.imread(filename)
h, w, _ = img.shape # assumes color image

# run tesseract, returning the bounding boxes
boxes = pytesseract.image_to_boxes(img)use
print(pytesseract.image_to_string(img)) #print identified text

# draw the bounding boxes on the image
for b in boxes.splitlines():
    b = b.split()
    cv2.rectangle(img, ((int(b[1]), h - int(b[2]))), ((int(b[3]), h - int(b[4]))), (0, 255, 0), 2)

plt.imshow(img)