Извлечение текста из изображения с помощью API Google Cloud Vision с использованием cv2 в Python - PullRequest
0 голосов
/ 20 мая 2019

Мы пытаемся извлечь текст из изображения с помощью google-cloud-vision API:

import io
import os
from google.oauth2 import service_account
from google.cloud import vision

# The name of the image file to annotate (Change the line below 'image_path.jpg' ******)
path = os.path.join(os.path.dirname(__file__), '3.jpg') # Your image path from current directory 


client = vision.ImageAnnotatorClient()

with io.open(path, 'rb') as image_file:
    content = image_file.read()

image = vision.types.Image(content=content)

response = client.text_detection(image=image)
texts = response.text_annotations
print('Texts:')

for text in texts:
    print(format(text.description))

В этом коде нам нужно, чтобы API считывал изображение только через функцию 'cv2'вместо использования функции 'io':

# Read image file
    with io.open(img_path, 'rb') as image_file:
        content = image_file.read()

Любое предложение будет полезным

1 Ответ

3 голосов
/ 20 мая 2019

Все, что вам нужно, - преобразовать массив numy, созданный из cv2, в байты, которые используются Google Vision API.Вот как вы это делаете:

import cv2 
with open(path, 'rb') as image_file:
    content1 = image_file.read()
image = cv2.imread(path)
success, encoded_image = cv2.imencode('.jpg', image)
content2 = encoded_image.tobytes()
image_cv2 = vision.types.Image(content=content2)
response =  client.text_detection(image=image_cv2)
texts = response.text_annotations
...