hytos / minorTools / gcloud_test.py @ e4c359d0
이력 | 보기 | 이력해설 | 다운로드 (2.76 KB)
1 |
def detect_text(path): |
---|---|
2 |
"""Detects text in the file."""
|
3 |
from google.cloud import vision |
4 |
import cv2 |
5 |
import numpy as np |
6 |
|
7 |
client = vision.ImageAnnotatorClient() |
8 |
|
9 |
with open(path, "rb") as image_file: |
10 |
content = image_file.read() |
11 |
|
12 |
_image = cv2.imread(path, 1)
|
13 |
|
14 |
image = vision.Image(content=content) |
15 |
|
16 |
response = client.text_detection(image=image, image_context={"language_hints": ["en"]}) |
17 |
#response = client.document_text_detection(image=image)
|
18 |
|
19 |
bounds = [] |
20 |
document = response.full_text_annotation |
21 |
|
22 |
for page in document.pages: |
23 |
for block in page.blocks: |
24 |
for paragraph in block.paragraphs: |
25 |
for word in paragraph.words: |
26 |
'''
|
27 |
for symbol in word.symbols:
|
28 |
if feature == FeatureType.SYMBOL:
|
29 |
bounds.append(symbol.bounding_box)
|
30 |
|
31 |
if feature == FeatureType.WORD:
|
32 |
bounds.append(word.bounding_box)
|
33 |
'''
|
34 |
_vertices = [(vertex.x,vertex.y) for vertex in word.bounding_box.vertices] |
35 |
cv2.rectangle(_image, _vertices[0], _vertices[2], (100, 100, 100), 2) |
36 |
cv2.putText(_image, ''.join([s.text for s in word.symbols]), (_vertices[0][0] + 30, (_vertices[0][1] - 10)), cv2.FONT_HERSHEY_PLAIN, 1, (100, 100, 100), 1) |
37 |
|
38 |
_vertices = [(vertex.x,vertex.y) for vertex in paragraph.bounding_box.vertices] |
39 |
cv2.rectangle(_image, _vertices[0], _vertices[2], (100, 100, 100), 2) |
40 |
|
41 |
#if feature == FeatureType.PARA:
|
42 |
# bounds.append(paragraph.bounding_box)
|
43 |
|
44 |
#if feature == FeatureType.BLOCK:
|
45 |
# bounds.append(block.bounding_box)
|
46 |
|
47 |
'''
|
48 |
texts = response.text_annotations
|
49 |
#print("Texts:")
|
50 |
|
51 |
for text in texts[1:]:
|
52 |
#print(f'\n"{text.description}"')
|
53 |
|
54 |
#vertices = [ f"({vertex.x},{vertex.y})" for vertex in text.bounding_poly.vertices ]
|
55 |
#print("bounds: {}".format(",".join(vertices)))
|
56 |
|
57 |
_vertices = [(vertex.x,vertex.y) for vertex in text.bounding_poly.vertices]
|
58 |
|
59 |
cv2.rectangle(_image, _vertices[0], _vertices[2], (100, 100, 100), 2)
|
60 |
cv2.putText(_image, text.description, (_vertices[0][0] + 30, (_vertices[0][1] - 10)), cv2.FONT_HERSHEY_PLAIN, 1, (100, 100, 100), 1)
|
61 |
'''
|
62 |
|
63 |
cv2.imwrite(path.replace('.png', '_res.png'), _image) |
64 |
|
65 |
if response.error.message:
|
66 |
raise Exception( |
67 |
"{}\nFor more info on error messages, check: "
|
68 |
"https://cloud.google.com/apis/design/errors".format(response.error.message)
|
69 |
) |
70 |
|
71 |
|
72 |
if __name__ == "__main__": |
73 |
import os |
74 |
path = 'E:\Projects\DTIPID\minorTools\gcloud'
|
75 |
path = os.path.join(path, '1.png')
|
76 |
detect_text(path) |
77 |
|