본문 바로가기
STUDY/YOLO

yolov4를 python으로 실행

by brown_board 2022. 5. 23.
728x90

학습시킨 yolov4-tiny모델을 python코드로 작성하여 실행하게 했다.

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
import cv2                       #영상처리를 하기 위한 라이브러리
import numpy as np               #박스를 그리고 좌표를 얻기 위한 라이브러리
# 웹캠 신호 받기
VideoSignal = cv2.VideoCapture(0)
 
captured_num = 0
text=''
 
#----------가중치 파일------------------------------------------------------------------------------------------------
YOLO_net = cv2.dnn.readNet('yolov4-tiny-hyeok_last.weights','yolov4-tiny-hyeok.cfg')
classes = []
with open('package.names'"r"as f:
    classes = [line.strip() for line in f.readlines()]
layer_names = YOLO_net.getLayerNames()
output_layers = [layer_names[i - 1for i in YOLO_net.getUnconnectedOutLayers()]
#output_layers = [layer_names[i[0] - 1] for i in YOLO_net.getUnconnectedOutLayers()]
#----------가중치 파일------------------------------------------------------------------------------------------------
 
while True:
    # 웹캠 프레임
    ret, frame = VideoSignal.read()
    frame = cv2.resize(frame,(416,416))
    h, w, c = frame.shape
    text=''
    # YOLO 입력
    blob = cv2.dnn.blobFromImage(frame, 0.00392, (416416), (000),True, crop=False)
    YOLO_net.setInput(blob)
    outs = YOLO_net.forward(output_layers)
 
    class_ids = []
    confidences = []
    boxes = []
 
    for out in outs:
 
        for detection in out:
 
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
 
            if confidence > 0.5:
                # Object detected
                center_x = int(detection[0* w)
                center_y = int(detection[1* h)
                dw = int((detection[2]) * w)
                dh = int((detection[3]) * h)
                # Rectangle coordinate
                x = int(center_x - dw / 2)
                y = int(center_y - dh / 2)
                boxes.append([x, y, dw, dh])
                confidences.append(float(confidence))
                class_ids.append(class_id)
 
    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.80.4)
 
 
    for i in range(len(boxes)):
        if i in indexes:
            x, y, w, h = boxes[i]
            label = str(classes[class_ids[i]])
            score = confidences[i]
 
            # 경계상자와 클래스 정보 이미지에 입력
            cv2.rectangle(frame, (x, y), (x + w, y + h), (00255), 1)
 
    cv2.imshow("YOLOv4", frame)
    if cv2.waitKey(1& 0xFF == ord('q'):
        break
    
VideoSignal.release()
cs
output_layers = [layer_names[i - 1for i in YOLO_net.getUnconnectedOutLayers()]
#output_layers = [layer_names[i[0] - 1] for i in YOLO_net.getUnconnectedOutLayers()]
이 부분이 있는데 원래 아래 코드로 실행이 됬었는데 안되서 위 코드로 바꾸었다. 웨지감자
 
1. cv2 설치

위와 같이 오류가 나오면 anaconda prompt창을 열고 pip install opencv-python입력

416x416인 상황에서 박스쳐진 중심값 좌표(x,y)를 반환하고 있다.
왼쪽위가 (0,0) 오른쪽 아래가 (416,416)이다. 지금 사진으로 보이는 택배의 중심값이 (343,277)언저리 인 것을 확인 할 수 있다.

728x90

'STUDY > YOLO' 카테고리의 다른 글

opencv gpu (2)  (0) 2022.05.24
opencv gpu (1)  (0) 2022.05.24
YOLO_Label사용  (0) 2022.05.20
anaconda 설치  (0) 2022.05.19
yolov4-tiny custom 학습  (0) 2022.05.13

댓글