PROGRAMMING

훈련 데이터 카메라 영상 적용 본문

OpenCV/머신비전 - 이미지 디텍팅

훈련 데이터 카메라 영상 적용

Raccoon2125 2020. 12. 28. 16:57

1. 웹카메라 연결

 

2. yolo_custom_test_video.py

import numpy as np
import cv2
import time

min_confidence = 0.5
width = 1280
height = 0
show_ratio = 1.0
title_name = 'Custom Yolo'
# Load Yolo
net = cv2.dnn.readNet("./machineVision/yolo_custom_test_video/model/custom-train-yolo_final.weights",
 "./machineVision/yolo_custom_test_video/custom/custom-train-yolo.cfg")
classes = []
with open("./machineVision/yolo_custom_test_video/custom/classes.names", "r") as f:
    classes = [line.strip() for line in f.readlines()]
color_lists = np.random.uniform(0, 255, size=(len(classes), 3))

layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

def detectAndDisplay(image):
    h, w = image.shape[:2]
    height = int(h * width / w)
    img = cv2.resize(image, (width, height))

    blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), swapRB=True, crop=False)

    net.setInput(blob)
    outs = net.forward(output_layers)
    
    confidences = []
    names = []
    boxes = []
    colors = []

    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > min_confidence:
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)

                x = int(center_x - w / 2)
                y = int(center_y - h / 2)

                boxes.append([x, y, w, h])
                confidences.append(float(confidence))
                names.append(classes[class_id])
                colors.append(color_lists[class_id])

    indexes = cv2.dnn.NMSBoxes(boxes, confidences, min_confidence, 0.4)
    font = cv2.FONT_HERSHEY_PLAIN
    for i in range(len(boxes)):
        if i in indexes:
            x, y, w, h = boxes[i]
            label = '{} {:,.2%}'.format(names[i], confidences[i])
            color = colors[i]
            print(i, label, x, y, w, h)
            cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
            cv2.putText(img, label, (x, y - 10), font, 1, color, 2)
    cv2.imshow(title_name, img)

capture = cv2.VideoCapture(0)
time.sleep(2.0)
if not capture.isOpened:
    print('### Error opening video ###')
    exit(0)
while True:
    ret, frame = capture.read()
    if frame is None:
        print('### No more frame ###')
        capture.release()
        break
    detectAndDisplay(frame)
    # 'q'를 누르면 카메라 종료
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

capture.release()
cv2.destroyAllWindows()

 

3. 결과 화면(동영상 캡처본)

chocolate 99.76%, milk 100.00%

 

'OpenCV > 머신비전 - 이미지 디텍팅' 카테고리의 다른 글

YOLO(Darknet Setup - Colab / cuDNN)  (0) 2021.01.02
YOLO(Game)  (0) 2021.01.02
YOLO (gum, milk, chocolate) 추가 자료  (0) 2020.12.24
YOLO (gum, chocolate, milk / 실습)  (0) 2020.12.24
YOLO (apple, orange / 교육)  (0) 2020.12.24
Comments