코딩걸음마

구글 Vision API로 이미지 내 텍스트를 인식하기! (파이썬) 본문

꿀팁 소스코드 저장소

구글 Vision API로 이미지 내 텍스트를 인식하기! (파이썬)

코딩걸음마 2022. 10. 25. 10:14
728x90

 

 

from urllib.parse import urlsplit, quote

#url 인코더
def transfrom_url(url):   

    url_info = urlsplit(url)
    encoded_url = f'{url_info.scheme}://{url_info.netloc}{quote(url_info.path)}'
    
    return encoded_url

def detect_text_url(uri):
    """Detects text in the file located in Google Cloud Storage or on the Web.
    """
    from google.cloud import vision
    import os
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "  ********발급받은 API 키 입력***** "
          
    client = vision.ImageAnnotatorClient()
    image = vision.Image()
    url = transfrom_url(uri)
    image.source.image_uri = uri

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

    for text in texts:
        print('\n"{}"'.format(text.description))

        vertices = (['({},{})'.format(vertex.x, vertex.y)
                    for vertex in text.bounding_poly.vertices])

        print('bounds: {}'.format(','.join(vertices)))

    if response.error.message:
        raise Exception(
            '{}\nFor more info on error messages, check: '
            'https://cloud.google.com/apis/design/errors'.format(
                response.error.message))

실행 예시

detect_text_url("https://i.ytimg.com/vi/ugYaarrjvlc/maxresdefault.jpg")

 

728x90
Comments