import io
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="future-shuttle-323208-1e6aebdb018d.json"
# Imports the Google Cloud client library
from google.cloud import vision
from PIL import Image
import cv2
write1=[]
write2=[]
for i in range(0,235):
# Instantiates a client
client = vision.ImageAnnotatorClient()
# The name of the image file to annotate
file_name = os.path.abspath("v2i/%d.png"%(i))
# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.text_detection(image=image)
texts = response.text_annotations
i_str=str(i)
filename='i2tvision/'+i_str+'.txt'
for text in texts:
write1.append('\n"{}"'.format(text.description))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in text.bounding_poly.vertices])
write2.append('bounds: {}'.format(','.join(vertices)))
#指定文字檔路徑
f = open(filename, 'w')
f.write(write1[i])
f.write(write2[i])
f.close()
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
#指定文字檔路徑
#i_str=str(i)
#filename='i2tvision/'+i_str+'.txt'
#f = open(filename, 'w')
#f.write(write1[i])
#f.write(write2[i])
#f.close()
My goal is to use google vision to convert multiple photos into multiple text files, but during the conversion process (in the for loop) I keep encountering a bug"runfile('/home/lab/chinese/i2tvision.py', wdir= '/home/lab/chinese') Traceback (most recent call last):
File "/home/lab/chinese/i2tvision.py", line 50, in f.write(write1[i])
IndexError: list index out of range" Is there any direction to solve this problem? Thank you
You don't need those two lists at all. Just write the lines as you generate them.
f = open(filename, 'w')
for text in texts:
f.write('\n"{}"'.format(text.description))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in text.bounding_poly.vertices])
f.write('bounds: {}'.format(','.join(vertices)))
f.close()