일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- Graph Cost
- list_display
- 카카오 API
- 코드포스
- 레지스터
- 리버싱
- 1557
- 알고리즘 대회
- Hello 2023
- vue3
- idpiframe_initialization_failed
- 기본키 변경
- 밑바닥부터 시작하는 딥러닝 1
- iupc
- 앳코더
- 인하대 프로그래밍 경진대회
- expand item
- django
- Flutter
- 넥토리얼
- Round 866
- shake!
- vue-google-login
- Codeforces Round 831 (Div. 1 + Div. 2)
- dart
- Good Bye 2022: 2023 is NEAR
- 카카오 로그인
- Div. 2
- 2022
- E - Hanging Hearts
- Today
- Total
pseong
텐서 플로우 2 객체 탐지 (object detection 2) 웹캠 사용 실습 본문
이미 학습된 모델을 가지고 윈도우에서 텐서 플로우 2를 이용하여 객체 탐지를 해 보자.
1. Object detection api 설치
먼저 Anaconda 여기에 들어가서 아나콘다를 설치하자.
윈도우 터미널에서 다음과 같이 콘다를 이용하여 파이썬 가상 환경을 만들자.
conda create -n tensorflow pip python=3.9
그런 다음 가상환경에 진입하자.
conda activate tensorflow
진입하고 난 후의 상황은 다음과 같다.
(tensorflow) C:\
가상 환경에 진입한 상태에서 다음 명령어를 통해 텐서 플로우를 설치하자.
pip install --ignore-installed --upgrade tensorflow
nvdia gpu를 사용한다면 cuda를 설치하여 gpu를 이용하자.
CUDA 11.2 에 들어가서 cuda 11.2를 설치하자.
그리고 cuDNN 여기에서 cuDNN v8.1.0 을 다운로드한다.
다운로드한 cuDNN를 방금 설치한 cuda 11.2 설치 폴더에 덮어쓰기를 해야 한다.
설치경로\NVIDIA GPU Computing Toolkit\CUDA\v11.2\
여기다가 덮어쓰기를 한다. 보통 설치경로는
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2\bin
기본적으로 여기에 설치가 된다.
환경 변수를 PATH를 추가해 주어야 하는데 환경변수 PATH에 다음과 같이 5개를 추가해 준다.
윈도우 PATH 추가 방법은 구글에 검색하면 잘 설명되어 있다.
- 설치경로\NVIDIA GPU Computing Toolkit\CUDA\v11.2\bin
- 설치경로\NVIDIA GPU Computing Toolkit\CUDA\v11.2\libnvvp
- 설치경로\NVIDIA GPU Computing Toolkit\CUDA\v11.2\include
- 설치경로\NVIDIA GPU Computing Toolkit\CUDA\v11.2\extras\CUPTI\lib64
- 설치경로\NVIDIA GPU Computing Toolkit\CUDA\v11.2\cuda\bin
이제 Tensorflow detection api를 설치해야 한다.
먼저 C:\Tensorflow 파일을 생성한다.
터미널을 열고 다음 명령어를 입력한다.
cd Tensorflow
이제 git clone 명령어를 통해 깃 레포지토리를 복사한다.
git clone https://github.com/tensorflow/models.git
그리고 protoc 을 다운로드한다. ( 가장 최신의 win64.zip 파일을 받으면 된다. )
C:\protoc에 압축을 해제한다.
그리고 압축해제경로\bin 을 환경변수 PATH에 추가한다.
새로운 터미널을 실행시키고 cd 명령어를 통해 TensorFlow\models\research 경로로 들어간다.
cd C:\TensorFlow\models\research
그리고 다음 명령어를 입력한다.
protoc object_detection/protos/*.proto --python_out=.
실행이 정상적으로 됐다면 아무런 출력도 나오지 않는다.
다시 cd 명령어를 통해 TensorFlow\models\research 경로로 들어간다.
cd C:\TensorFlow\models\research
그리고 다음 명령어를 통해 object detection api를 설치하자.
cp object_detection/packages/tf2/setup.py .
python -m pip install --use-feature=2020-resolver .
마지막으로 다시 cd 명령어를 통해 TensorFlow\models\research 경로로 들어간다.
그리고 다음 명령어를 통해 object detection api가 잘 설치가 됐는지 확인하자.
cd C:\TensorFlow\models\research
python object_detection/builders/model_builder_tf2_test.py
ok가 잘 떴다면 정상적으로 설치가 완료됐다.
models 파일은 object detection api가 설치가 끝났으므로 이제 필요가 없지만
추 후 학습된 모델을 다시 학습시키고 export 할 때 필요한 코드가 들어 있으니 삭제하지 않는 게 좋다.
2. 사전 학습된 모델로 테스트 진행하기
이제 사전 학습된 zoo 모델을 가지고 간단하게 객체 탐지를 돌려보자.
C:\TensorFlow 폴더 아래에 data\models 폴더를 만들자.
그리고 그 models 폴더 안에 zoo 의 EfficientDet D0 512x512 를 다운받고
C:\TensorFlow\data\models 폴더안에 압축을 해제하자.
그리고 다음 파일을 다운받고 C:\TensorFlow\data\models\efficientdet_d0_coco17_tpu-32 에다가 압축을 해제하자.
그리고 C:\TensorFlow 에다가 cam.py 파이썬 파일을 하나 생성하자.
현재까지 Tensorflow 폴더의 상태는 다음과 같다.
TensorFlow/
├─ data/
├─ models/
├─ efficientdet_d0_coco17_tpu-32/
├─ checkpoint/
├─ saved_model/
├─ mscoco_label_map.pbtxt
└─ pipeline.config
├─ models/
├─ community/
├─ official/
├─ orbit/
├─ research/
├─ tensorflow_models/
├─ AUTHORS
├─ CODEOWNERS
├─ CONTRIBUTING
├─ ISSUES
├─ LICENSE
└─ README
└─ cam.py
cam.py 에 아래의 코드를 붙여 넣자.
from object_detection.utils import visualization_utils as viz_utils
from object_detection.utils import label_map_util
from object_detection.utils import config_util
from object_detection.builders import model_builder
import tensorflow as tf
import numpy as np
import cv2
import os
import time
# 모델, 라벨 지정
MODEL_NAME = 'efficientdet_d0_coco17_tpu-32'
LABEL_FILENAME = 'mscoco_label_map.pbtxt'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.get_logger().setLevel('ERROR')
DATA_DIR = os.path.join(os.getcwd(), 'data')
MODELS_DIR = os.path.join(DATA_DIR, 'models')
[os.mkdir(dir) for dir in [DATA_DIR, MODELS_DIRR] if not os.path.exists(dir)]
PATH_TO_CKPT = os.path.join(MODELS_DIR, os.path.join(MODEL_NAME, 'checkpoint/'))
PATH_TO_CFG = os.path.join(MODELS_DIR, os.path.join(MODEL_NAME, 'pipeline.config'))
PATH_TO_LABELS = os.path.join(MODELS_DIR, os.path.join(MODEL_NAME, LABEL_FILENAME))
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
configs = config_util.get_configs_from_pipeline_file(PATH_TO_CFG)
model_config = configs['model']
detection_model = model_builder.build(model_config=model_config, is_training=False)
ckpt = tf.compat.v2.train.Checkpoint(model=detection_model)
ckpt.restore(os.path.join(PATH_TO_CKPT, 'ckpt-0')).expect_partial()
@tf.function
def detect_fn(image):
image, shapes = detection_model.preprocess(image)
prediction_dict = detection_model.predict(image, shapes)
detections = detection_model.postprocess(prediction_dict, shapes)
return detections, prediction_dict, tf.reshape(shapes, [-1])
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
cap = cv2.VideoCapture(0)
while True:
ret, image_np = cap.read()
image_np_expanded = np.expand_dims(image_np, axis=0)
input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
detections, predictions_dict, shapes = detect_fn(input_tensor)
label_id_offset = 1
image_np_with_detections = image_np.copy()
viz_utils.visualize_boxes_and_labels_on_image_array(
image_np_with_detections,
detections['detection_boxes'][0].numpy(),
(detections['detection_classes'][0].numpy() + label_id_offset).astype(int),
detections['detection_scores'][0].numpy(),
category_index,
use_normalized_coordinates=True,
max_boxes_to_draw=200,
min_score_thresh=.35,
agnostic_mode=False)
cv2.imshow('object detection', image_np_with_detections)
# 종료 키 : q
if cv2.waitKey(5) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
그리고 웹캠을 컴퓨터에 연결한 후 다음 명령어를 통해 실행해 보자.
cd C:\Tensorflow
conda activate tensorflow
python cam.py
'인공지능 > 딥러닝' 카테고리의 다른 글
mnist 이용한 손글씨 인식 cnn 딥러닝 구현하기 (0) | 2022.01.25 |
---|