[python] ImageAI 사용해서 image Object Detection(1)

2021. 1. 22. 22:59·개발/Python
728x90

ImageAI

객체 탐지 관련해서 아무것도 모르는 초보자도 쉽게 할 수 있는 모듈이 있다. 이미지 또는 영상에서 객체 탐지를 해주는 AI 모듈이다. 탐지율, 정확도 꽤 높게 나오는 것 같고, 흐린 사진에서도 탐지율이 높은 것 같다.

이미지를 이미 학습한 모델 파일을 다운로드하여 사용하는 방식, 직접 학습해서 자신만의 용도로 분류하는 모델을 만드는 방식도 있다. 이 중에서 본인에게 필요한 방식을 사용하면 된다. 나는 학습한 모델 파일을 다운로드하여(yolo.h5) 사용했다.

자세한 설치 및 사용설명은 github를 참고하세요.

https://github.com/OlafenwaMoses/ImageAI

개발환경

- ubuntu 16.04
- Python 3.7.6

pip install

최대한 버전을 똑같이 해줘야, 처음 보는 오류가 발생하지 않는다.

- Tensorflow 2.4.0
- OpenCV
- Keras 2.4.3

$ pip install tensorflow==2.4.0
$ pip install keras==2.4.3 numpy==1.19.3 pillow==7.0.0 scipy==1.4.1 h5py==2.10.0 matplotlib==3.3.2 opencv-python keras-resnet==0.2.0
$ pip install imageai --upgrade

Object Detection

나는 객체 탐지(Object Detection)를 사용했고,  models에 사용한 파일은 yolo.h5을 사용했다. 이 외에도 TinyYOLOv3, RetinaNet 방법이 있고, 각 방식에 대한 설명을 해준다.

* RetinaNet (Size = 145 mb, 더 긴 감지 시간으로 고성능 및 정확성 )
* YOLOv3 (Size = 237 mb, 중간 정도의 감지 시간으로 중간 정도의 성능 및 정확도)
* TinyYOLOv3 (Size = 34 mb, 빠른 감지 시간으로 속도 및 중간 성능에 최적화)

모든 객체를 탐지하여 결과를 알려준다.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os ,cv2
from imageai.Detection import ObjectDetection

execution_path = os.getcwd()

detector = ObjectDetection()
detector.setModelTypeAsYOLOv3()
detector.setModelPath( os.path.join(execution_path , "models","yolo.h5"))
detector.loadModel()

input_image = os.path.join(execution_path , "input/13.jpg") # 입력이미지
output_image_path = os.path.join(execution_path ,"output/imagenew_1_2021") # 결과 이미지

detections = detector.detectCustomObjectsFromImage( input_image= input_image,output_image_path=output_image_path,
minimum_percentage_probability=30, display_percentage_probability=False, display_object_name=False)
# 최소 정확도가 30% 이상인 결과 출력, 결과이미지에 정확도 출력 여부,  결과이미지에 객체명 출력 여부


for eachObject in detections:
	print( " {} : {} ".format(eachObject["name"], eachObject["percentage_probability"]))
	print("--------------------------------")

최소 정확도가 30% 이상, 정확도, 객체명을 출력하지 않았다. 다양한 옵션들을 조절하여, 결과를 뽑을 수 있다.

ImageAI 결과

Custom Object Detection

detector.CustomObjects를 설정하여 원하는 객체만 탐지할 수 있다.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os ,cv2
from imageai.Detection import ObjectDetection

execution_path = os.getcwd()

detector = ObjectDetection()
detector.setModelTypeAsYOLOv3()
detector.setModelPath( os.path.join(execution_path , "models","yolo.h5"))
detector.loadModel()

input_image = os.path.join(execution_path , "input/13.jpg") # 입력이미지
output_image_path = os.path.join(execution_path ,"output/imagenew_1_2021") # 결과 이미지

# 사람, 자전거 , 차, 오토바이, 비행기, 버스, 기차, 트럭, 보트 만 탐지결과에 반영(탐지)
custom_objects = detector.CustomObjects(person=True, bicycle=True, car=True, motorcycle=True, airplane=True, bus=True, train=True, truck=True, boat=True)

detections = detector.detectCustomObjectsFromImage(custom_objects=custom_objects, 
input_image= input_image,output_image_path=output_image_path,
minimum_percentage_probability=30, display_percentage_probability=False, display_object_name=False)
# 최소 정확도가 30% 이상인 결과 출력, 결과이미지에 정확도 출력 여부,  결과이미지에 객체명 출력 여부

for eachObject in detections:
	print( " {} : {} ".format(eachObject["name"], eachObject["percentage_probability"]))
	print("--------------------------------")

 

ImageAI결과 - bounding box제거 방법(detectCustomObjectsFromImage)

$ cd ./.local/lib/python3.6/site-packages

####### [가상- python virtual environment]
$ cd /opt/image_ai/env/lib/python3.6/site-packages
$ sudo cp __init__.py /opt/image_ai/env/lib/python3.6/site-packages/imageai/Detection/tmp_test/

####### [리눅스]
$ cd /usr/local/lib/python3.5/dist-packages
$ cd imageai/Detection
$ sudo mkdir -p tmp_test/
$ sudo cp __init__.py tmp_test/
$ sudo vi __init__.py

######
### :875 - draw_box(detected_copy, detection_details, color=color) 삭제 및 주석 처리
######

 


객체 탐지 결과에 모자이크를 반영해서 사용했다. 모자이크 하는 방법은 이어서 작성할 예정이다.

이렇게 간단하게, 이미지 분석을 하고, 정확도도 알 수 있고 정말 좋은 것 같다. 그렇다고 성능이 안 좋은 것도 아니다. 성능도 좋고 여러 가지 옵션을 설정하여 사용할 수도 있다. 🤓

이런 걸 만들어 주신 개발자님께 감사합니다. 👍👍👍👍👍👍👍

 

728x90
저작자표시 비영리 변경금지 (새창열림)

'개발 > Python' 카테고리의 다른 글

[python/linux] 파이썬 nohup 사용법(백그라운드,데몬실행)  (0) 2022.12.09
[오라클/파이썬] DPI-1047오류 해결방법(oracledb)  (0) 2022.10.12
[Python] pip install 오류('cp949' codec can't decode byte 0xe2 in position 1091: illegal multibyte sequence)  (0) 2022.04.04
[Linux/Ubuntu] Ubuntu 20.04에 python3.7 설치  (0) 2021.01.27
[python] 오프라인에서 pip install 하여 package 설치하기  (0) 2020.11.03
'개발/Python' 카테고리의 다른 글
  • [오라클/파이썬] DPI-1047오류 해결방법(oracledb)
  • [Python] pip install 오류('cp949' codec can't decode byte 0xe2 in position 1091: illegal multibyte sequence)
  • [Linux/Ubuntu] Ubuntu 20.04에 python3.7 설치
  • [python] 오프라인에서 pip install 하여 package 설치하기
호이호이209
호이호이209
이것저것 기록하는 메모장
    250x250
  • 호이호이209
    R=VD
    호이호이209
    • R=VD전체글 (83)
      • 개발 (63)
        • Linux (19)
        • 머신러닝 (10)
        • Git (6)
        • Python (9)
        • 프로그래밍 언어 (2)
        • Docker (5)
        • ETC (12)
      • 일상기록 (20)
        • 여행 (5)
        • 일상-이모저모 (8)
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
호이호이209
[python] ImageAI 사용해서 image Object Detection(1)
상단으로

티스토리툴바