inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[개정판] 딥러닝 컴퓨터 비전 완벽 가이드

Faster-RCNN Pretrained 모델로 Video Inference 실행

서버에서 설치해서 돌리는 중 에러가 발생해서 문의드립니다.

814

lee seungmin

작성한 질문수 8

0

안녕하세요. 별도의 서버에서 pretrained 모델 기반으로 video inference 실행을 하는 중에서 계속 다음과 같은 에러가 발생하여 문의드립니다. 

colab이 아닌 별도 서버에서 실행하였고, 선생님이 주신 코드를 파일 경로 부분만 수정해서 사용하였습니다. 

-------------------

import sys
sys.path.append("/home/jongmin/mmdetection")

# config 파일과 pretrained 모델을 기반으로 Detector 모델을 생성. 
from mmdet.apis import init_detector, inference_detector
import cv2
import matplotlib.pyplot as plt

labels_to_names_seq = {0:'person',1:'bicycle',2:'car',3:'motorbike',4:'aeroplane',5:'bus',6:'train',7:'truck',8:'boat',9:'traffic light',10:'fire hydrant',
                        11:'stop sign',12:'parking meter',13:'bench',14:'bird',15:'cat',16:'dog',17:'horse',18:'sheep',19:'cow',20:'elephant',
                        21:'bear',22:'zebra',23:'giraffe',24:'backpack',25:'umbrella',26:'handbag',27:'tie',28:'suitcase',29:'frisbee',30:'skis',
                        31:'snowboard',32:'sports ball',33:'kite',34:'baseball bat',35:'baseball glove',36:'skateboard',37:'surfboard',38:'tennis racket',39:'bottle',40:'wine glass',
                        41:'cup',42:'fork',43:'knife',44:'spoon',45:'bowl',46:'banana',47:'apple',48:'sandwich',49:'orange',50:'broccoli',
                        51:'carrot',52:'hot dog',53:'pizza',54:'donut',55:'cake',56:'chair',57:'sofa',58:'pottedplant',59:'bed',60:'diningtable',
                        61:'toilet',62:'tvmonitor',63:'laptop',64:'mouse',65:'remote',66:'keyboard',67:'cell phone',68:'microwave',69:'oven',70:'toaster',
                        71:'sink',72:'refrigerator',73:'book',74:'clock',75:'vase',76:'scissors',77:'teddy bear',78:'hair drier',79:'toothbrush' }


def get_detected_img(modelimg_array,  score_threshold=0.3is_print=True):
      # 인자로 들어온 image_array를 복사. 
  draw_img = img_array.copy()
  bbox_color=(02550)
  text_color=(00255)

  # model과 image array를 입력 인자로 inference detection 수행하고 결과를 results로 받음. 
  # results는 80개의 2차원 array(shape=(오브젝트갯수, 5))를 가지는 list. 
  results = inference_detector(modelimg_array)

  # 80개의 array원소를 가지는 results 리스트를 loop를 돌면서 개별 2차원 array들을 추출하고 이를 기반으로 이미지 시각화 
  # results 리스트의 위치 index가 바로 COCO 매핑된 Class id. 여기서는 result_ind가 class id
  # 개별 2차원 array에 오브젝트별 좌표와 class confidence score 값을 가짐. 
  for result_indresult in enumerate(results):
    # 개별 2차원 array의 row size가 0 이면 해당 Class id로 값이 없으므로 다음 loop로 진행. 
    if len(result) == 0:
      continue
    
    # 2차원 array에서 5번째 컬럼에 해당하는 값이 score threshold이며 이 값이 함수 인자로 들어온 score_threshold 보다 낮은 경우는 제외. 
    result_filtered = result[np.where(result[:, 4] > score_threshold)]
    
    # 해당 클래스 별로 Detect된 여러개의 오브젝트 정보가 2차원 array에 담겨 있으며, 이 2차원 array를 row수만큼 iteration해서 개별 오브젝트의 좌표값 추출. 
    for i in range(len(result_filtered)):
      # 좌상단, 우하단 좌표 추출. 
      left = int(result_filtered[i0])
      top = int(result_filtered[i1])
      right = int(result_filtered[i2])
      bottom = int(result_filtered[i3])
      caption = "{}{:.4f}".format(labels_to_names_seq[result_ind], result_filtered[i4])
      cv2.rectangle(draw_img, (lefttop), (rightbottom), color=bbox_colorthickness=2)
      cv2.putText(draw_imgcaption, (int(left), int(top - 7)), cv2.FONT_HERSHEY_SIMPLEX0.37text_color1)
      if is_print:
        print(caption)

  return draw_img


# config 파일을 설정하고, 다운로드 받은 pretrained 모델을 checkpoint로 설정. 
config_file = './configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py'
checkpoint_file = './mmdetection/checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth'

model = init_detector(config_filecheckpoint_filedevice='cuda:2')

img = '/demo/demo.jpg'
img_arr  = cv2.imread(img)

detected_img = get_detected_img(modelimg_arr,  score_threshold=0.5is_print=True)
# detect 입력된 이미지는 bgr임. 이를 최종 출력시 rgb로 변환 
detected_img = cv2.cvtColor(detected_imgcv2.COLOR_BGR2RGB)

plt.figure(figsize=(1212))
plt.imshow(detected_img)

------------------------------
아래 내용입니다. 해당 내용에서 대해서 검색해보았을 때는 잘못된 메모리에 접근해서 그렇다고 하는데.. 잘 이해가 되지 않아 문의드립니다. 

RuntimeError: CUDA error: invalid device function

Segmentation fault (core dumped)

mmdection python 별도서버 에러 머신러닝 배워볼래요? 딥러닝 tensorflow keras 컴퓨터-비전

답변 1

0

권 철민

안녕하십니까, 

CUDA Library에서 내주는 segmentation fault라 원인은 정확히 알 수 없습니다. 주로 GPU 메모리 관련 이슈로 발생합니다. 

먼저, 단일 이미지는 잘 Detect가 되는지요? 만일 그렇다면

1. nvidia-smi 등으로 현재 GPU의 메모리가 어느정도 인지 확인해 주시고, Video frame을 계속해서 detect할때 GPU memory를 어느정도나 사용하는지 확인하시는게 좋을 것 같습니다.  또한 GPU  H/W Memory가 4G 아래이면 Config의 batch_size를 4 이상 키우지 않도록 해주십시요. H/W GPU Memory가 작으면 이미지 사이즈도 작게 해주십시요.  

단일 이미지의 Detect 부터 문제라면 mmdetection이나 cuda 등의 설치시 호환 버전이 안맞을 수 있으니,  https://github.com/open-mmlab/mmdetection/blob/master/docs/get_started.md 을 참조하시어 cuda version에 맞게 mmdetection을 설치해 주시기 바랍니다. 

감사합니다. 

강의 환경설정 질문

0

43

2

Custom Dataset에서의 polygon 정보 관련

0

86

3

cvat.ai 보안 수준이 궁금합니다

0

81

2

캐클 nucleus 챌린지 runpod 실습 코드 에러 질문드립니다.

0

96

3

추론 결과의 Precision(또는 mAP) 평가 방법

0

86

2

mmdetection mask rcnn inferenct 실습 시 runpod 템플릿 관해서 질문드립니다.

0

61

2

runpod에서 google drive 연결 시 오류 발생

0

110

2

로드맵 선택

0

67

1

mmcv

0

60

2

Anchor box의 Positive 처리 위치

0

63

2

해당 강의 runpod 적용 후 에러 제보드립니다

0

87

2

run pod credit 관련 제보

0

101

2

mmdetection 2.x과 3.x 호환 관련 표기

0

78

2

mm_faster_rcnn_train_kitti.ipynb 실행 오류

0

100

3

질문 드립니다.

0

83

3

mm_faster_rcnn_train_coco_bccd 실행 오류 질문드립니다.

0

80

1

강사님께 수정을 제안드리고 싶은 것이 있습니다.

0

95

1

google automl efficientdet 다운로드 및 설치 오류

0

75

1

이상 탐지에 사용할 비전 기술 조언 부탁드립니다.

0

104

2

OpenCV 관련 질문드립니다.

0

72

2

mmcv 설치관련해서 문의드려요

0

334

3

강의 구성 관련해서 질문이 있습니다

1

138

2

모델 변환 성능 질문드립니다.

0

123

1

NMS 로직 문의 드려요

0

115

2