🤍 전 강의 25% 할인 중 🤍

2024년 상반기를 돌아보고 하반기에도 함께 성장해요!
인프런이 준비한 25% 할인 받으러 가기 >>

  • 카테고리

    질문 & 답변
  • 세부 분야

    컴퓨터 비전

  • 해결 여부

    미해결

Fast RCNN- NMS 적용 코드

21.01.16 22:52 작성 조회수 266

0

안녕하세요. Fast RCNN Opencv Detection에서 NMS 적용을 후처리로 해보고 싶어서 코드를 짜봤는데, 결과가 NMS 안한 것은 17개, 한 것은 14개로 나왔는데 다음과 같이 코드를 짰는데 맞을까요? 감사합니다

import time

def get_detected_img(cv_net, img_array, score_threshold, nms_threshold, use_copied_array=True, is_print=True):
    
    rows = img_array.shape[0]
    cols = img_array.shape[1]
    
    draw_img = None
    if use_copied_array:
        draw_img = img_array.copy()
    else:
        draw_img = img_array
    
    cv_net.setInput(cv2.dnn.blobFromImage(img_array, swapRB=True, crop=False))
    
    start = time.time()
    cv_out = cv_net.forward()
    
    green_color=(0, 255, 0)
    red_color=(0, 0, 255)
    
    class_ids = []
    confidences = []
    boxes = []
    
    # detected 된 object들을 iteration 하면서 정보 추출
    for detection in cv_out[0,0,:,:]:
        score = float(detection[2])
        class_id = int(detection[1])
        
        # detected된 object들의 score가 함수 인자로 들어온 score_threshold 이상만 추출
        if score > score_threshold:
            # detected된 object들은 scale된 기준으로 예측되었으므로 다시 원본 이미지 비율로 계산
            left = detection[3] * cols
            top = detection[4] * rows
            right = detection[5] * cols
            bottom = detection[6] * rows
            
            width = right - left
            height = bottom - top
            
            confidences.append(float(score))
            class_ids.append(class_id)
            boxes.append([left, top, width, height])
    
    idxs = cv2.dnn.NMSBoxes(boxes, confidences, score_threshold, nms_threshold)
    
    if len(idxs) > 0:
        for i in idxs.flatten():
            box = boxes[i]
            left = box[0]
            top = box[1]
            width = box[2]
            height = box[3]
            
            # labels_to_names 딕셔너리로 class_id값을 클래스명으로 변경. opencv에서는 class_id + 1로 매핑해야함.
            caption = "{}: {:.4f}".format(labels_to_names_0[class_ids[i]], confidences[i])
            #cv2.rectangle()은 인자로 들어온 draw_img에 사각형을 그림. 위치 인자는 반드시 정수형.
            cv2.rectangle(draw_img, (int(left), int(top)), (int(left+width), int(top+height)), color=green_color, thickness=2)
            cv2.putText(draw_img, caption, (int(left), int(top - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, red_color, 1)
            print(caption)
         
    if is_print:
        print('Detection 수행시간:',round(time.time() - start, 2),"초")

    return draw_img

답변 1

답변을 작성해보세요.

0

안녕하십니까,

별 이슈가 없어 보입니다.

감사합니다.

채널톡 아이콘