본문 바로가기
기타👨🏻‍💻/AI

[OCR] Google Vision Ai 적용 ( 이미지 분석 - Python )

by 텅빈비니 2024. 3. 20.
반응형

안녕하세요🐶

빈지식 채우기의 비니🙋🏻‍♂️ 입니다.

 

요즘 AI에 대해 많은 관심과 더불어 실생활에 사용이 되는 경우가 많아졌습니다.

실제로 AI 기술을 제공하는 오픈 플랫폼도 많이 등장하고 있으며,

다수의 기업에서 진행되고 있는 프로젝트에서 사용이 되고 있습니다.

 

오늘은 많은 오픈 플랫폼 중 Google 에서 제공되는 Vision AI에 대해 알아보도록 하겠습니다.


1. Google Vision AI 란.

 

https://cloud.google.com/vision?hl=ko

 

cloud.google.com

Vision AI

 

Google 에서 제공해주는 머신러닝 기반 이미지 분석 AI 이다.

많은 기능이 있으나 위와 같이 4개의 기능으로 요약할 수 있습니다.

 

우리는 Vision API를 통해 실제 기능으로 사용할 수 있으며,

아래 이미지는 Vision AI 홈페이지에서 제공하는 분석 예시 입니다.

Vision API 예시

  • Object, Labels, Text, Properties, Safe Search 가 있습니다.
  • 위 이미지의 예시는 Object(객체) 가 어떤 것이 있는지 확인하고 있습니다.

Vision API 제공 기능

  • Vision API에서 제공하는 기능들은 위와 같습니다.
  • 우리는 제공되는 API를 통해 이미지 분석을 실제 체험해볼 수 있습니다.

2. Google Cloud Platform 등록하기

Vision API를 사용하기 위해서는 Google Cloud Platform에 가서 프로젝트를 등록해야 합니다.

 

Google 클라우드 플랫폼

로그인 Google 클라우드 플랫폼으로 이동

accounts.google.com

  •  Vision API를 사용할 프로젝트를 생성합니다.

  • 프로젝트 생성 후 API를 사용을 하기위한 3가지 설정에 대해 말씀드리도록 하겠습니다.

2-1. 결제 등록하기

  • 계정 만들기를 통해 결제 계정을 등록시킵니다.
  • 실제 결제 수단과 연결되지만 자동 구독(결제)는 없으니 안심하시고 등록하셔도 됩니다.

2-2. 서비스키 발급받기

  • API 를 사용하기 위해 JSON 키를 발급받아야 합니다.
  • IAM 및 관리자 탭에서 위와 같이 수행합니다.
    • JSON 키는 아래와 같이 프로젝트 내부에 위치시키는 것을 권장드립니다.

2-3. API 사용 설정

 

Google Cloud console

 

console.cloud.google.com

  • 위 첨부된 링크를 따라 Cloud Vision API 사용을 허용합니다.

3. Vision API 사용하기

API 사용 방법에 대해 차근차근 알아보도록 하겠습니다!

 

3-1. Python 가상환경 구축

각각의 프로젝트에 필요한 모듈(라이브러리)를 별도의 로컬 환경에 설치하여 사용
글로벌 설치 시 의존성 때문에 관리가 힘듬
// env 가상환경 구축
python3 -m venv env

env 가상환경 추가

  • env 가상환경 설치
// 가상환경 사용
source ./env/bin/activate

가상환경 시작

  • env 가상환경 시작
// 가상환경 종료
deactivate

가상환경 종료

  • env 가상환경 종료 ( 모듈 설치 후 )

 

3-2. Google Vision API 설치

// Google Vision API 설치
pip install --upgrade google-cloud-vision

  • env 내부 lib 에 Google 모듈이 설치가 된다.

 

3-3. gcloud CLI 설치

 

gcloud CLI 설치  |  Google Cloud CLI 문서

의견 보내기 gcloud CLI 설치 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 이 페이지에는 Google Cloud CLI 설치를 선택하고 유지하기 위한 안내가 포함되어 있습

cloud.google.com

  • 명령어를 통해 gcloud CLI 를 초기화 시켜줍니다.

4. API 사용하기 ( Python )

OCR에 사용된 이미지

  • OCR에 사용되는 이미지입니다.
import os

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = '/Users/Vision/vision-api-xxxx.json'
  • 발급받았던 서비스키(JSON) 을 환경변수로 입력합니다.
imgPath = "../../images/combine.png"	# 사용할 이미지 로컬 위치

def detect_text(path):
    from google.cloud import vision	# Google Vision 라이브러리 사용

    client = vision.ImageAnnotatorClient()

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

    image = vision.Image(content=content)

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

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

        vertices = [
            f"({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(imgPath)

  • 위와 같이 이미지에 있는 Combine 이라는 값을 정확히 가지고 오는 것을 확인할 수 있습니다.

그 외에도!

이미지 속성, 라벨 인식, 로고 인식, 객체 인식 과 같은 기능도 사용 가능하니, 

아래에 첨부된 소스 확인 부탁드립니다!

더보기
import os

 

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = '/Users/ptk/Sean/Project/Study/AI/Google-Vision/vision-api-test-xxxxx.json'

 

imgPath = "../images/combine.png"

 

def detect_text(path):
"""Detects text in the file."""
from google.cloud import vision

 

client = vision.ImageAnnotatorClient()

 

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

 

image = vision.Image(content=content)

 

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

 

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

 

vertices = [
f"({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)
)

 

def detect_properties(path):
"""Detects image properties in the file."""
from google.cloud import vision

 

client = vision.ImageAnnotatorClient()

 

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

 

image = vision.Image(content=content)

 

response = client.image_properties(image=image)
props = response.image_properties_annotation
print("Properties:")

 

for color in props.dominant_colors.colors:
print(f"fraction: {color.pixel_fraction}")
print(f"\tr: {color.color.red}")
print(f"\tg: {color.color.green}")
print(f"\tb: {color.color.blue}")
print(f"\ta: {color.color.alpha}")

 

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

 

def detect_labels(path):
"""Detects labels in the file."""
from google.cloud import vision

 

client = vision.ImageAnnotatorClient()

 

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

 

image = vision.Image(content=content)

 

response = client.label_detection(image=image)
labels = response.label_annotations
print("Labels:")

 

for label in labels:
print(label.description)

 

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

 

def detect_logos(path):
"""Detects logos in the file."""
from google.cloud import vision

 

client = vision.ImageAnnotatorClient()

 

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

 

image = vision.Image(content=content)

 

response = client.logo_detection(image=image)
logos = response.logo_annotations
print("Logos:")

 

for logo in logos:
print(logo.description)

 

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

 

def localize_objects(path):
"""Localize objects in the local image.

 

Args:
path: The path to the local file.
"""
from google.cloud import vision

 

client = vision.ImageAnnotatorClient()

 

with open(path, "rb") as image_file:
content = image_file.read()
image = vision.Image(content=content)

 

objects = client.object_localization(image=image).localized_object_annotations

 

print(f"Number of objects found: {len(objects)}")
for object_ in objects:
print(f"\n{object_.name} (confidence: {object_.score})")
print("Normalized bounding polygon vertices: ")
for vertex in object_.bounding_poly.normalized_vertices:
print(f" - ({vertex.x}, {vertex.y})")



# 텍스트 인식
# detect_text(imgPath)
 
# 이미지 속성
# detect_properties(imgPath)

 

# 라벨 인식
# detect_labels(imgPath)

 

# 로고 인식
# detect_logos(imgPath)

 

# 객체 인식
# localize_objects(imgPath)

감사합니다.


참고

반응형