tensorflow에서 자신의 이미지 그림을 읽는 방법 (Queue를 통해batch 생성)
2759 단어 tensorflow 노트
여기에서 각본을 써서 스스로 배우고 공고히 하는 데 편리하다.(코드는 Python3 기반)
그림 파일의 저장 경로는 다음과 같습니다.
``
ROOT_FOLDER
|-------- SUBFOLDER (CLASS 0)
| |
| | ----- image1.jpg
| | ----- image2.jpg
| | ----- etc...
|
|-------- SUBFOLDER (CLASS 1)
| |
| | ----- image1.jpg
| | ----- image2.jpg
| | ----- etc...
```
루트 디렉터리에 각 종류의 폴더를 만들고, 각 종류의 그림을 대응하는 폴더 아래에 놓습니다
import tensorflow as tf
import os
#
Root_path = './'
# , ,
NUM_CLASS = 2
IMAGE_HEIGHT = 28
IMAGE_WIDTH = 28
IMAGE_CHANNELS = 3 # =3, =1
def read_iamge(Root_path, batch_size):
imagepaths = []
labels = []
label = 0
classes = sorted(os.walk(Root_path).__next__()[1])
for c in classes:
c_dir = os.path.join(Root_path, c)
walk = os.walk(c_dir).__next__()[2]
for sample in walk:
if sample.endswith('.jpg') and sample.endswith('.jpeg'):
imagepaths.append(os.path.join(c_dir, sample))
labels.append(label)
label += 1
# iamgepaths labels tf
imagepaths = tf.convert_to_tensor(imagepaths, tf.string)
labels = tf.convert_to_tensor(labels, tf.int32)
# Queue
imagepath, label = tf.train.slice_input_producer([imagepaths, labels], shuffle=True)
# ,
image = tf.read_file(imagepath)
image = tf.image.decode_jpeg(image, channels=IMAGE_CHANNELS)
# ( [0,255] [-1,1])
image = tf.image.resize_images(image, size=[IMAGE_HEIGHT, IMAGE_WIDTH])
image = image*1.0/127.5 - 1.0
# batch
X, Y = tf.train.batch([image, label], batch_size=batch_size, num_threads=4, capacity=batch_size*8)
return X, Y
그중 tf.train.slice_input_producer () 함수는 tensorlist에서 랜덤으로 tensor를 선택합니다
tf.train.batch () 함수는 디자인 요구에 부합되는batch를 만들 것입니다
tf 때문에.train.batch ()는Queue를 기반으로 하는 것이기 때문에 사용할 때Queue 작업 tf를 시작해야 합니다.train.start_queue_runners()