프로젝트명 : 카메라를 이용해서 개와 고양이를 구분하는 안드로이드 앱



  


 



APK : https://drive.google.com/file/d/1mT7PBNToRTvC2yj6GKB00djyNFnycMW0/view?usp=sharing

훈련 시간에 비해 실제 고양이와 모니터에 출력된 강아지사진 모두 잘 작동 합니다.




PS.안드로이드 프로젝트 파일이 용량이 커서 업로드가 안되네요. 혹시 코드 필요하신분은 댓글 달아주세요.



< 모델 작성 >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# -*- coding: utf-8 -*-
"""cats_dogs_android.ipynb
Automatically generated by Colaboratory.
Original file is located at
    https://colab.research.google.com/drive/1gPyCFufUR4cGkEH95om6w6Pl1pf7uDmn
"""
 
import numpy as np
import pandas as pd 
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator, load_img
from keras.utils import to_categorical
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import random
import os
 
FAST_RUN = False
IMAGE_WIDTH=128
IMAGE_HEIGHT=128
IMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)
IMAGE_CHANNELS=3
 
filenames = os.listdir("./dogs-vs-cats/train")
categories = []
for filename in filenames:
    category = filename.split('.')[0]
    if category == 'dog':
        categories.append(1)
    else:
        categories.append(0)
 
df = pd.DataFrame({
    'filename': filenames,
    'category': categories
})
 
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
 
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization
import keras.backend as K
 
# with tf.device("device:XLA_GPU:0"):
model = Sequential()
 
model.add(Conv2D(32, (33), activation='relu', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS)))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(22)))
model.add(Dropout(0.25))
 
model.add(Conv2D(64, (33), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(22)))
model.add(Dropout(0.25))
 
model.add(Conv2D(128, (33), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(22)))
model.add(Dropout(0.25))
 
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax')) # 2 because we have cat and dog classes
 
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
 
model.summary()
 
from keras.callbacks import EarlyStopping, ReduceLROnPlateau
earlystop = EarlyStopping(patience=10)
learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc'
                                            patience=2
                                            verbose=1
                                            factor=0.5
                                            min_lr=0.00001)
callbacks = [earlystop, learning_rate_reduction]
 
df["category"= df["category"].replace({0'cat'1'dog'})
 
train_df, validate_df = train_test_split(df, test_size=0.20, random_state=42)
train_df = train_df.reset_index(drop=True)
validate_df = validate_df.reset_index(drop=True)
 
total_train = train_df.shape[0]
total_validate = validate_df.shape[0]
batch_size=16
 
train_datagen = ImageDataGenerator(
    rotation_range=15,
    rescale=1./255,
    shear_range=0.1,
    zoom_range=0.2,
    horizontal_flip=True,
    width_shift_range=0.1,
    height_shift_range=0.1
)
 
train_generator = train_datagen.flow_from_dataframe(
    train_df, 
    "./dogs-vs-cats/train/"
    x_col='filename',
    y_col='category',
    target_size=IMAGE_SIZE,
    class_mode='categorical',
    batch_size=batch_size
)
 
validation_datagen = ImageDataGenerator(rescale=1./255)
validation_generator = validation_datagen.flow_from_dataframe(
    validate_df, 
    "./dogs-vs-cats/train/"
    x_col='filename',
    y_col='category',
    target_size=IMAGE_SIZE,
    class_mode='categorical',
    batch_size=batch_size
)
 
example_df = train_df.sample(n=1).reset_index(drop=True)
example_generator = train_datagen.flow_from_dataframe(
    example_df, 
    "./dogs-vs-cats/train/"
    x_col='filename',
    y_col='category',
    target_size=IMAGE_SIZE,
    class_mode='categorical'
)
 
plt.figure(figsize=(1212))
for i in range(015):
    plt.subplot(53, i+1)
    for X_batch, Y_batch in example_generator:
        image = X_batch[0]
        plt.imshow(image)
        break
plt.tight_layout()
plt.show()
 
epochs=3 if FAST_RUN else 20
history = model.fit_generator(
    train_generator, 
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=total_validate//batch_size,
    steps_per_epoch=total_train//batch_size,
    callbacks=callbacks
)
model.save("./my_model")
 
def convert_model(model_path, tflite_path):
    converter = tf.lite.TFLiteConverter.from_keras_model_file(model_path)
    flat_data = converter.convert()
 
    with open(tflite_path, 'wb') as f:
        f.write(flat_data)
 
 
convert_model('./my_model''./cats_and_dogs.tflite')
 
cs


+ Recent posts