갈루아의 반서재

10줄짜리 파이썬 코드로 간단히 사진 속의 차량 대수를 카운트 해보자. 먼저 아래의 라이브러리가 설치되어 있어야 한다. 설치 이전이라면 각각의 링크를 참고해 설치하도록 한다. 

opencv-python
cvlib
matplotlib
tensorflow
keras

 

TensorFlow

An open source machine learning library for research and production.

www.tensorflow.org

 

Home - Keras Documentation

Keras: The Python Deep Learning library You have just found Keras. Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano. It was developed with a focus on enabling fast experimentation. Be

keras.io

 

Matplotlib: Python plotting — Matplotlib 3.1.1 documentation

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shells, the Jupyter noteb

matplotlib.org

 

cvlib

A high level, easy to use, open source computer vision library for python

pypi.org

 

opencv-python

Wrapper package for OpenCV python bindings.

pypi.org

상기 라이브러리 설치와 관련하여 다음 포스팅을 참고해도 좋다.

필수 파이썬 라이브러리를 불러오고, 저장소로부터 이미지를 읽은 후, 해당 이미지속의 사물을 식별한다.  그리고 식별된 사물에 박스를 치고, 라벨링한다.  마지막으로 이미지 속의 자동차 수를 카운트한 다음 출력한다. 전체 코드는 다음과 같이 10줄이다.

import cv2
import matplotlib.pyplot as plt
import cvlib as cv
from cvlib.object_detection import draw_bbox
im = cv2.imread('cars_1.jpeg')
bbox, label, conf = cv.detect_common_objects(im)
output_image = draw_bbox(im, bbox, label, conf)
plt.imshow(output_image)
plt.show()
print('Number of cars in the image is '+ str(label.count('car')))

원래 이미지 cars_1.jpeg

식별 결과는 다음과 같다.

Number of cars in the image is 29

다른 이미지를 가지고도 테스트해자.

Number of cars in the image is 15

Number of cars in the image is 10

확장자가 틀린 경우에는 다음과 같은 에러가 발생하므로, 해당 에러가 발생하는 파일 이름을 다시 확인해본다. 

AttributeError                            Traceback (most recent call last)
<ipython-input-9-f98a1313245b> in <module>
      4 from cvlib.object_detection import draw_bbox
      5 im = cv2.imread('automobile.jpeg')
----> 6 bbox, label, conf = cv.detect_common_objects(im)
      7 output_image = draw_bbox(im, bbox, label, conf)
      8 plt.imshow(output_image)

~/anaconda3/envs/lindy/lib/python3.7/site-packages/cvlib/object_detection.py in detect_common_objects(image, confidence, nms_thresh, model)
     58 def detect_common_objects(image, confidence=0.5, nms_thresh=0.3, model='yolov3'):
     59 
---> 60     Height, Width = image.shape[:2]
     61     scale = 0.00392
     62 

AttributeError: 'NoneType' object has no attribute 'shape'

 

원문소스 https://towardsdatascience.com/count-number-of-cars-in-less-than-10-lines-of-code-using-python-40208b173554

 

Count Number of Cars in Less Than 10 Lines of Code Using Python

Make your own cars counter using this simple code

towardsdatascience.com