벌써 2일차가 왔다. 내일이면 금요일이고, 주말이 훅 지나가고 나면 바로 또 제출의 시기가 당겨온다..
그래서 오늘 다행인건 그나마? 진도가 어느정도는 나갔다고 생각한다.
오늘목표는 머신러닝 모델을 찾고, 그 모델로 여러가지 테스트를 해볼 생각이여는데 , 그래도 어느정도는 성공을 한 것 같다.
또한 파이선에서 두개의 모델을 돌려서, 첫번째 모델이 분류를 하지 못하면 두번째 모델이 분류를 하게끔 만들어 놓았다.
그나마 한시름 놓았지만 아직 할일이 산더미 처럼 남아있다.
가상환경 셋팅이 정말 오래걸렸다 여기서도 에러가 많이 나서 중간에 싹지웠따가 다시 까는 불상사가 발생하였다. 또한 GPU로 설치를 하다보니 설치속도가 너무나도 오래걸렸다 CPU는 바로바로 설치를 하였다
우선 첫번째 모델 yolov5 이다
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
# image = cv2.imread('misc/test2.jpg')
image = cv2.imread('static/img/img/123123.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()
# step 3 - unwrap the predictions to get the object detections
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)
if 32 in class_ids:
result = True
ct = "ball"
elif 34 or 35 in class_ids:
result = False
ct = "baseball"
else:
result = True
ct = "error"
# 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("config_files/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()
print(result_class_ids)
print(result)
if 34 or 35 in class_ids:
print(ct)
cv2.imshow('cut image', dst_photo)
cv2.waitKey()
첫번째 모델에서 공이 나오면, 그리고 내가 지정해논 조건이 통과하지 못하면 다음 모델로 넘어가게끔 설정을 해 놓았다 result = True, False 로 간단하게 할 수 있었다.
그리고 두번째 모델
if result == True:
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
model = tf.keras.models.load_model('static/model/model.h5')
model = tf.keras.models.load_model('static/model/model.h5')
# model.summary()
label_code = {'baseball': 0, 'basketball': 1, 'soccer': 2, 'volleyball': 3}
label_decode = ['baseball', 'basketball', 'soccer', 'volleyball']
test_datagen = ImageDataGenerator(rescale=1. / 255)
test_dir = 'static/img'
test_generator = test_datagen.flow_from_directory(
test_dir,
# target_size 는 학습할때 설정했던 사이즈와 일치해야 함
target_size=(224, 224),
color_mode="rgb",
shuffle=False,
class_mode=None,
batch_size=1
)
pred = model.predict(test_generator)
# y_pred = np.argmax(pred, axis=1)
# y_pred_class = dict((v,k) for k,v in test_generator.class_indices.items())
# print(y_pred_class)
print(pred)
print(np.argmax(pred))
ct =label_decode[np.argmax(pred)]
print(ct)
두번째 모델이다, 우선 이모델을 정확도가 많이 떨여저서 따로 학습을 시켜줘야 한다. 우리가 yolo 에서 구분하지 못한 sport 카테고리를 여기서 한번더 분류를 시켜서 최종적인 카테고리를 분류한다!