TensorFlow에서 이미지 크기 조정

Anika Tabassum Era 2024년2월15일
  1. TensorFlow에서 단일 이미지 크기 조정
  2. TensorFlow에서 일련의 이미지 크기 조정
TensorFlow에서 이미지 크기 조정

OpenCV, Pillow, TensorFlow 등과 같은 라이브러리를 통해 이미지를 조작할 수 있습니다. TensorFlow는 지속적인 업데이트와 GPU와의 향상된 호환성으로 인해 더욱 집중됩니다.

TensorFlow 버전 1x와 버전 2x에는 여러 이미지 작업을 수행하기 위한 서로 다른 클래스와 메서드가 있습니다. 일부 메서드는 버전 2x에서 구문적으로 업데이트되었습니다.

다음 섹션에서는 두 가지 예를 설명합니다. 하나는 단일 이미지에서 버전 2x로 처리됩니다.

다음 예에는 일련의 이미지가 있는 TensorFlow 버전 1x가 포함됩니다. 그 부분으로 넘어가 보겠습니다.

TensorFlow에서 단일 이미지 크기 조정

이 경우 Google Colab을 환경으로 사용했습니다. Google Colab이 TensorFlow 버전 1x를 지원하지 않고 버전 2x만 가져오도록 지정합니다.

처음에 드라이브가 마운트되었으므로 이미지 가져오기가 활성화되었습니다.

이미지 경로를 가져온 후 TensorFlow 이미지로 로드했습니다. 크기 조정 작업은 여러 이미지 형식에서 발생하지 않습니다. 대신 해당 픽셀 값이 있는 배열로 변환해야 합니다.

다음 단계에서는 이미지의 특정 높이와 너비를 선언하고 TensorFlow의 resize() 메서드에서 해당 값을 전달합니다. 나중에 배열을 이미지로 다시 변환하고 이미지 품질이 크기 조정에 따라 달라지는 경우 시각화하기 위해 플롯합니다.

코드 조각:

from google.colab import drive

drive.mount("/content/drive")
import tensorflow as tf
import matplotlib.pyplot as plt
image_path = "/content/drive/MyDrive/IMG/pizza.jpg"
img = tf.keras.utils.load_img(image_path)
plt.imshow(img)
print(img.size)
image_array = tf.keras.preprocessing.image.img_to_array(img)
new_img = tf.image.resize(image_array, (70, 70))
resized_img = tf.keras.preprocessing.image.array_to_img(new_img)
plt.imshow(resized_img)

출력:

TensorFlow 1에서 단일 이미지 크기 조정

TensorFlow 2에서 단일 이미지 크기 조정

TensorFlow에서 일련의 이미지 크기 조정

이 예제에서는 Jupyter Notebook을 사용합니다. 필요한 종속성 및 메서드는 TensorFlow 버전 1x에서 사용할 수 있습니다.

이러한 방법은 버전 2x에서 지속적으로 업데이트되지만 원활한 작업을 위해 이전 방법을 사용하는 것이 좋습니다.

필요한 패키지를 설치하고 가져왔습니다. 이 경우 TensorFlow 버전은 1.15.8입니다.

이 경우 이미지는 문자열로 가져오고 나중에 tf.train.string_input_producer()로 전달되어 파일 대기열을 얻습니다.

파일 판독기를 초기화한 후 이름과 해당 내용을 수신합니다. 내용은 나중에 jpeg 형식으로 디코딩됩니다.

일반적으로 TensorFlow는 이산 코사인 변환을 입력의 기본값으로 사용합니다. 그런 다음 이미지를 플로팅하고 마지막으로 크기를 조정합니다.

코드 조각:

import matplotlib.pyplot as plt
import tensorflow as tf
import os

tf.__version__
image_path = "D:M"
categ = ["coffee"]

for c in categ:
    path = os.path.join(image_path, c)
    for img in os.listdir(path):
        image = [os.path.join(path, img)]

queue = tf.train.string_input_producer(image)

reader = tf.WholeFileReader()
name, content = reader.read(queue)
images = tf.image.decode_jpeg(content, channels=3)
print(images.shape)
images = tf.cast(images, tf.float32)
resized_images = tf.image.resize_images(images, (224, 224))
print(resized_images.shape)

출력:

TensorFlow에서 일련의 이미지 크기 조정

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook