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

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

我想在网站截图中突出显示特定的单词/句子。

截取屏幕截图后,我使用

pytesseract
cv2
提取文本。效果很好,我可以获得有关它的文本和数据。

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)

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

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

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

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

python-3.x computer-vision ocr python-tesseract
2个回答
8
投票

您可以使用

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)


0
投票

我希望这能为问题提供正确的解决方案,以突出显示图像中的文本。无论如何,这已经晚了,但对某人有用。

import cv2,re
import pytesseract


filename = 'quotes1.jpg'
text_search = "happiness" 

# read the image 
img = cv2.imread(filename)

# run tesseract, returning the bounding boxes
data = pytesseract.image_to_data(img, output_type='dict')
print(data)
boxes = len(data['level'])

for i in range(boxes):
    if re.search(text_search , data['text'][i] , re.IGNORECASE):
        overlay = img.copy()
        (x, y, w, h) = data['left'][i], data['top'][i], data['width'][i], data['height'][i]
        cv2.rectangle(overlay, (data['left'][i], data['top'][i]), (data['left'][i]+data['width'][i], data['top'][i]+data['height'][i]),(255,0,0), -1) 
        alpha = 0.4  # Transparency factor.
        # Following line overlays transparent rectangle over the image
        img_new = cv2.addWeighted(overlay, alpha, img, 1 - alpha, 0)
cv2.imwrite("output.jpg",img_new) 

输出: enter image description here

谢谢您!

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