LoginSignup
1
1

YOLOv7で画像にオブジェクトカウンターをつける方法

Last updated at Posted at 2023-12-04

YOLOv7で画像にオブジェクトカウンターをつける方法をメモしておきます。
T. Nukuiさんの記事を参考にしました。

YOLOv7では、物体検出を行うことができます。
従来のコードでは、画像にオブジェクトカウンターをつけることはできません。
そこで、画像にオブジェクトカウンターをつけることができるコードを調べたところ、T. Nukuiさんの記事を見つけました。
T. Nukuiさんの記事ではmuratali016さんのコードが使われており、私もmuratali016さんのコードを使います。

従来のコード

Google Colaboratoryにて実行しました。
ランタイム->ランタイムのタイプを変更->T4 GPUを選択

from google.colab import drive
drive.mount('/content/drive')
%cd "/content/drive/MyDrive"
!git clone https://github.com/WongKinYiu/yolov7
%cd "/content/drive/MyDrive/yolov7"
!pip install -r requirements.txt

バウンディングボックスの色を指定するためにdetect.pyの62行目に以下のコードを挿入します。

detect.py
# 62行目
colors[0] = (204, 122, 122)
colors[27] = (255, 102, 102)

物体検出(結果はyolov7/runs/detectに保存される)

%cd "/content/drive/MyDrive/yolov7"
!python detect.py --weights yolov7.pt --conf 0.3 --img-size 640 --source "/content/drive/MyDrive/yolov7/inference/images/zidane.jpg"

zidane.jpg

この画像が出力されます。
オブジェクトカウンターはついていないことがわかります。

画像にオブジェクトカウンターをつける

detect_and_count.pyをyolov7ディレクトリに配置します。
バウンディングボックスの色を指定するためにdetect_and_count.pyの79行目に以下のコードを挿入します。

detect_and_count.py
# 79行目
colors[0] = (204, 122, 122)
colors[27] = (255, 102, 102)

そして、以下のコードを実行します。

%cd "/content/drive/MyDrive/yolov7"
!python detect_and_count.py --weights yolov7.pt --conf 0.3 --img-size 640 --source "/content/drive/MyDrive/yolov7/inference/images/zidane.jpg"

zidane.jpg

右下に黄色のオブジェクトカウンターがつきました。
カウンターの色を白色に変えるため、detect_and_count.pyの29行目を以下のように書き換えます。

detect_and_count.py
# 29行目
cv2.putText(im0, str(a) ,(int(align_right),align_bottom), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),1,cv2.LINE_AA) # colorを(255,255,255)に変更

以下のコードをもう一回実行します。

%cd "/content/drive/MyDrive/yolov7"
!python detect_and_count.py --weights yolov7.pt --conf 0.3 --img-size 640 --source "/content/drive/MyDrive/yolov7/inference/images/zidane.jpg"

zidane.jpg

カウンターの色が白色になりました。

muratali016さんのコードにより、画像にオブジェクトカウンターをつけることができました。
また、コードを書き換えることにより、カウンターの色を変えることができました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1