본문 바로가기
- 배움이 있는 삶/- Software | English

Image classification python program

by story of interesting 2021. 3. 17.
반응형


# https://codetorial.net/tensorflow/classifying_the_cats_and_dogs.html

# 데이타 set 살펴보기 : 경로 및 파일명
import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import tensorflow as tf

# 1)
# beer/coke 데이터셋 경로 지정
train_beer_dir = '.image/beer/Right_image'
train_coke_dir = '.image/coke/Right_image'

# beer 파일 이름 리스트
train_beer_names = os.listdir(train_beer_dir)
print(train_beer_names[:10])

# coke 파일 이름 리스트
train_coke_names = os.listdir(train_coke_dir)
print(train_coke_names[:10])

# beer/coke 총 이미지 파일 개수
print('total training beer images:', len(os.listdir(train_beer_dir)))
print('total training coke images:', len(os.listdir(train_coke_dir)))

# 2)
# 이미지 확인하기 : horse -> beer, human --> coke
nrows = 4
ncols = 4

pic_index = 0

fig = plt.gcf()
fig.set_size_inches(ncols * 4, nrows * 4)

pic_index += 8
next_beer_pix = [os.path.join(train_beer_dir, fname) for fname in train_beer_names[pic_index-8:pic_index]]
next_coke_pix = [os.path.join(train_coke_dir, fname) for fname in train_coke_names[pic_index-8:pic_index]]


for i, img_path in enumerate(next_beer_pix+next_coke_pix):
sp = plt.subplot(nrows, ncols, i + 1)
sp.axis('Off')
img = mpimg.imread(img_path)
plt.imshow(img)

plt.show() # 8개씩 beer coke가 새로운 창으로 출력됨

# 3)
# 이제 이미지 분류와 훈련을 위한 합성곱 신경망 (Convolutional Neural Network)을 구성합니다.
model = tf.keras.models.Sequential([
# The first convolution
tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(300, 300, 3)),
tf.keras.layers.MaxPool2D(2, 2),
# The second convolution
tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
tf.keras.layers.MaxPool2D(2, 2),
# The third convolution
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPool2D(2, 2),
# The fourth convolution
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPool2D(2, 2),
# The fifth convolution
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPool2D(2, 2),
# Flatten
tf.keras.layers.Flatten(),
# 512 Neuron (Hidden layer)
tf.keras.layers.Dense(512, activation='relu'),
# 1 Output neuron
tf.keras.layers.Dense(1, activation='sigmoid')
])

model.summary()

반응형