Skip to content

Instantly share code, notes, and snippets.

@Simseounghyeon
Created September 7, 2020 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Simseounghyeon/17432fd99549d97222af56c7ea5ee9ef to your computer and use it in GitHub Desktop.
Save Simseounghyeon/17432fd99549d97222af56c7ea5ee9ef to your computer and use it in GitHub Desktop.
iu?suzy?
from flask import Flask, render_template, request
import cv2
import numpy
import gc
from keras import backend as K
import face_detection
import predict
from mtcnn.mtcnn import MTCNN
from keras.models import load_model
detector = MTCNN()
model = load_model('./static/keras_model/1layer_128_1_best(1)-SGD.h5')
app = Flask(__name__, static_url_path="/static")
print("시작 ")
print("로딩됨")
@app.route('/')
def render_file():
gc.collect()
return render_template('upload.html')
@app.route('/file_uploaded',methods = ['GET', 'POST'])
def upload_file():
try:
print("세선 클리어 시작")
K.clear_session()
print("세선 클리어 끝")
if request.method == 'POST': # POST 방식으로 전달된 경우
f = request.files['upload_image'].read()
# # 파일 객체 혹은 파일 스트림을 가져오고, html 파일에서 넘겨지는 값의 이름을 file1으로 했기 때문에 file1임.
# 업로드된 파일을 특정 폴더에저장하고,
# convert string data to numpy array
npimg = numpy.fromstring(f, dtype=numpy.uint8)
# convert numpy array to image
img = cv2.imdecode(npimg, cv2.IMREAD_COLOR)
if img.shape[0] > 500 or img.shape[1] > 500:
if img.shape[0] > img.shape[1]:
bigger = img.shape[0]
else :
bigger = img.shape[1]
scale_percent = (bigger - 500) *100 / bigger
width = int(img.shape[1] * (100-scale_percent) / 100)
height = int(img.shape[0] * (100- scale_percent) / 100)
dim = (width, height)
img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
print(img.shape)
# 이거때문에 face_extract 때문에 올라감
face_extract = face_detection.input_image(detector,img)
print("얼굴추출 완료")
if len(face_extract) == 0:
print("얼굴인식 못했음")
return render_template('fail_back.html')
else:
result, k = predict.prediction(model,face_extract)
iu_percent = round(float(k[0][0] * 100), 3)
suzy_percent = round(float(k[0][1]) * 100, 3)
# return send_file(file_object, mimetype='image/jpeg')
if iu_percent > suzy_percent:
return render_template('result.html', image_file="image/result_iu.jpg", not_similler="수지",
not_similler_percent=suzy_percent, similler="아이유", similler_percent=iu_percent)
else:
return render_template('result.html', image_file="image/result_suzy.jpg", not_similler="아이유",
not_similler_percent=iu_percent, similler="수지", similler_percent=suzy_percent)
else:
return render_template('fail_back.html')
except :
return render_template('fail_back.html')
if __name__ == '__main__':
# debug를 True로 세팅하면, 해당 서버 세팅 후에 코드가 바뀌어도 문제없이 실행됨.
app.run(threaded=True)
def face_eye_trace(data,result_list):
try:
result = result_list[0]
x = int(result['box'][0])
y = int(result['box'][1])
if x < 0:
x = 0
if y < 0:
y = 0
width = int(result['box'][2])
height = int(result['box'][3])
img3 = data[y:y + height, x:x + width]
return img3
except:
return
def input_image(k,pixels_image):
try:
# 이것때문에 memory 증가===============
faces = k.detect_faces(pixels_image)
print(len(faces))
if len(faces) == 0:
return []
elif len(faces) == 1 :
face_detection = face_eye_trace(pixels_image,faces)
return face_detection
else :
print("다수의 얼굴이 인식되어 종료했습니다.")
return []
except:
print("얼굴 인식을 하지 못하였습니다.")
return []
import cv2
import numpy as np
# 2. 모델 불러오기
def prediction(model,k):
try :
img = cv2.resize(k, dsize=(100, 100), interpolation=cv2.INTER_AREA)
x=[]
x.append(img/256)
img = np.array(x)
print("예측")
k=model.predict_on_batch(img)
for i in k:
if i[0] > i[1]:
return "아이유",k
else:
return "수지",k
except :
print("예측에서 예외발생")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment