GPT4 이미지 생성해보기

이두원·2023년 5월 8일
1
post-thumbnail

지난번 Auto gpt에서 GPT-4를 사용하려 했으나 문제가 발생했다. 그 때 GPT-4의 데이터가 2021년 9월까지만 업데이트되어 있는 것이 오류의 원인이라 생각했지만, 사실은 다른 이유였다. 알고 보니 GPT-4를 API로 사용하기 위해서는 결제 외에도 별도의 대기 목록 신청이 필요했다. 어제 드디어 승인 메일을 받게 되어, 이제 GPT-4를 활용하여 프로젝트를 진행할 수 있게 되었다.

  1. 목표설정
    gpt-4는 이미지 입출력을 지원한다고 하는데, 그렇다면 전에 gpt-3에 이미지를 인식시키기 위해 객체의 라벨, 정확도 및 바운딩 박스 좌표 같은걸 추출하지 않아도, 그냥 이미지를 넣으면 된다는 감격스러운 이야기이다.
    그렇다면 이미지를 입력하면 DALL·E models을 사용해 그 이미지의 변형본을 생성해 출력하는 코드를 써보자.

  2. 코딩

from io import BytesIO
from PIL import Image

# Read the image file from disk and resize it
image = Image.open("image.png")
width, height = 256, 256
image = image.resize((width, height))

# Convert the image to a BytesIO object
byte_stream = BytesIO()
image.save(byte_stream, format='PNG')
byte_array = byte_stream.getvalue()

response = openai.Image.create_variation(
  image=byte_array,
  n=1,
  size="1024x1024"
)

일단 Openai 홈페이지에 있는 예시 코드를 가져와보자. 코알못인 내가 봐도 알 수 있을 정도로 직관적이다. response의 n값은 생성되는 이미지의 갯수로 10개 이하의 값이어야 한다는 것만 주의하자.
그런데 정작 결과물이 어디 저장되는지 보이지 않는다. 검색해보니 API를 호출하는 코드 내부에 저장된다고 한다. 하지만 나는 컴퓨터에 바로 저장이 되야 안심이 되니, 코드를 조금 수정해보자.

image.save("/path/to/image.png") 를 가장 마지막에 추가하면 된다는데, SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape , 경로에 한글이 있어서 오류가 난다. 경로 중 '바탕화면' 이라는 글자 때문인데, 다음에 윈도우 설치할 땐 영어로 해야겠다는 생각을 하며 한글이 포함되지 않도록 경로를 바꾼다.

그러니 결과가 나왔는데, 왼쪽부터 원본, 생성된 이미지이다. 사람 얼굴이 살바도르 달리의 작품 마냥 초현실적인 사소한 문제를 빼면 버스, 사람, 건물 3가지 큰 요소를 인식하고 이미지를 생성했다.

이미지 입출력이 잘 된다는 걸 확인했으니, 결과물의 이름을 원본이름 + _generated 를 붙이도록 코드를 추가하고, 다음 프로젝트를 진행하자.

from io import BytesIO
from PIL import Image
import openai
import requests
import os

original_file_name = "bus.jpg"

# Read the image file from disk and resize it
image = Image.open(original_file_name)
width, height = 256, 256
image = image.resize((width, height))

# Convert the image to a BytesIO object
byte_stream = BytesIO()
image.save(byte_stream, format='PNG')
byte_array = byte_stream.getvalue()
openai.api_key_path = "C:\\Users\endnj\gpt_files\gpt4_key.txt"
response = openai.Image.create_variation(
  image=byte_array,
  n=1,
  size="1024x1024"
)
# Extract the image URL from the response
image_url = response['data'][0]['url']

# Download the image using the URL
response = requests.get(image_url)

# Convert the downloaded image data to a PIL.Image object
image_data = response.content
generated_image = Image.open(BytesIO(image_data))

# Create a new file name based on the original file name
new_file_name = os.path.splitext(original_file_name)[0] + "_generated.png"

# Save the image
generated_image.save("C:\\Users\\endnj\\gpt_files\\generated_images\\" + new_file_name)
profile
AI 초보 개발자

3개의 댓글