오늘도 어김없이 오류와 싸우고있다...
우선 yolov5 는 db와 연결을 해서 거기있는 이미지로 분류를 하고 있지만
케라스로 학습시킨 모델이 좀처럼 말을 듣지 않는다.....
정말 어떻게 해야 될지 모르겠다 ㅜㅜㅜ
우선 내일 부터 일요일까지 이작업을 계속 진행 할 예정이지만,, 어떻게든 내일까지는 해결을 해야 할 것 같다.
def result_ct():
def format_yolov5(frame):
row, col, _ = frame.shape
_max = max(col, row)
result = np.zeros((_max, _max, 3), np.uint8)
result[0:row, 0:col] = frame
return result
all = db.joinsport.find_one({'name': "hajin"})
photo = all['name']
image = cv2.imread(f'static/img/img/{photo}.jpg')
input_image = format_yolov5(image) # making the image square
blob = cv2.dnn.blobFromImage(input_image, 1 / 255.0, (640, 640), swapRB=True)
net.setInput(blob)
predictions = net.forward()
class_ids = []
confidences = []
boxes = []
output_data = predictions[0]
image_width, image_height, _ = input_image.shape
x_factor = image_width / 640
y_factor = image_height / 640
for r in range(25200):
row = output_data[r]
confidence = row[4]
if confidence >= 0.4:
classes_scores = row[5:]
_, _, _, max_indx = cv2.minMaxLoc(classes_scores)
class_id = max_indx[1]
if (classes_scores[class_id] > .25):
confidences.append(confidence)
class_ids.append(class_id)
x, y, w, h = row[0].item(), row[1].item(), row[2].item(), row[3].item()
left = int((x - 0.5 * w) * x_factor)
top = int((y - 0.5 * h) * y_factor)
width = int(w * x_factor)
height = int(h * y_factor)
box = np.array([left, top, width, height])
boxes.append(box)
# elif class_id == 35:
# confidences.append(confidence)
# class_ids.append(class_id)
# x, y, w, h = row[0].item(), row[1].item(), row[2].item(), row[3].item()
# left = int((x - 0.5 * w) * x_factor)
# top = int((y - 0.5 * h) * y_factor)
# width = int(w * x_factor)
# height = int(h * y_factor)
# box2 = np.array([left, top, width, height])
# boxes.append(box2)
class_list = []
with open("static/model/yolov5/classes.txt", "r") as f:
class_list = [cname.strip() for cname in f.readlines()]
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.25, 0.45)
result_class_ids = []
result_confidences = []
result_boxes = []
for i in indexes:
result_confidences.append(confidences[i])
result_class_ids.append(class_ids[i])
result_boxes.append(boxes[i])
for i in range(len(result_class_ids)):
box = result_boxes[i]
class_id = result_class_ids[i]
cv2.rectangle(image, box, (0, 255, 255), 2)
cv2.rectangle(image, (box[0], box[1] - 20), (box[0] + box[2], box[1]), (0, 255, 255), -1)
cv2.putText(image, class_list[class_id], (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 0))
###### 볼 체크하기 ########
# x = box[0] + box[2]
# y = box[1] + box[3]
# x2 = box2[0] + box2[2]
# y2 = box2[1] + box2[3]
dst_photo = image.copy()
# dst_photo2 = image[box2[1]:y2, box2[0]:x2].copy()
if 32 in result_class_ids:
result_learnig = True
result_ct = "ball"
if 32 and 35 in result_class_ids:
result_learnig = False
result_ct = "baseball"
if 34 or 35 in result_class_ids:
result_learnig = False
result_ct = "baseball"
else:
result_learnig = True
result_ct = "error"
print(result_class_ids)
print(result_ct)
우선 yolo모델이다. 이모델은 거의다 테스트가 된 상태이고 문제없이 잘 작동 하는 것 같다.
문득 든 생각이지만 케라스 모델을 다시 가져와서 테스트만 반복하고 있는 느낌인데,,
무언가 방법이 잘못되었다고 생각한다
내일은 다시 코드를 뜯어보고 다시 들여다 봐야겠다...
추가로 오늘 퀴즈시간, 오늘은 그래도 퀴즈를 어느정도 푼 것 같다. 처음인가,,?
계속하고 있던 작업이라 그런지 눈에 잘 들어온 것 같다
from flask import Flask, render_template, request, redirect, url_for, jsonify
from datetime import datetime
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
from pymongo import MongoClient
import numpy as np
import os
client = MongoClient('mongodb+srv://test:sparta@cluster0.oaadu.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.time
app = Flask(__name__)
model = tf.keras.models.load_model('static/model/model.h5')
@app.route('/')
def home():
return render_template('index.html')
@app.route('/fileupload', methods=['POST'])
def file_upload():
file = request.files['file_give']
extension = file.filename.split('.')[-1]
today = datetime.now()
mytime = today.strftime('%Y-%m-%d-%H-%M-%S')
filename = f'{mytime}'
save_to = f'static/img/img/{filename}.{extension}'
file.save(save_to)
doc = {
'photo': filename
}
db.joinsport.insert(doc)
return jsonify({'result': 'success'})
@app.route('/result')
def result_ct():
test_datagen = ImageDataGenerator(rescale=1. / 255)
test_dir = 'static/img'
test_generator = test_datagen.flow_from_directory(
test_dir,
# target_size 는 학습할때 설정했던 사이즈와 일치해야 함
target_size=(256, 256),
color_mode="rgb",
shuffle=False,
# test 셋의 경우, 굳이 클래스가 필요하지 않음
# 학습할때는 꼭 binary 혹은 categorical 로 설정해줘야 함에 유의
class_mode=None,
batch_size=1)
pred = model.predict(test_generator)
if pred[-1] > 0.5:
result = '강아지'
else:
result = '고양이'
print(pred)
print(result)
return render_template('index.html', result=result)
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
숙제 코드.