Python影像辨識筆記(九之五):透過Google Colab在雲端運行YOLOv3

Source: Deep Learning on Medium

本文Colab

更改Runtime

#預設是以CPU執行,我們將它改成GPURuntime->Change runtime type->GPU

連接Google Drive

from google.colab import drivedrive.mount('/content/gdrive') 
# 請點擊網址,選擇 Google 帳號登入,然後將授權碼貼回輸入框中
!ln -fs /content/gdrive/My\ Drive /app

解壓縮cuDNN

!tar -xzvf /app/darknet/cuDNN/cudnn-10.0-linux-x64-v7.5.0.56.tgz -C /usr/local/!chmod a+r /usr/local/cuda/include/cudnn.h# 檢查是否安裝成功!cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2

下載並編譯 Darknet(只需要執行一次)

%cd /content/!git clone https://github.com/kriyeng/darknet/ darknet_source%cd darknet_source# 修改 Darknet 設定,符合 Colab 環境!sed -i "s/GPU=0/GPU=1/g" Makefile!sed -i "s/CUDNN=0/CUDNN=1/g" Makefile!sed -i "s/OPENCV=0/OPENCV=1/g" Makefile# 編譯!make# 將編譯完成的執行檔複製回 Google Drive!cp ./darknet /app/darknet!cp ./darknet /content/darknet%cd /content

將相關檔案複製到darknet的資料夾中

將雲端硬碟中,已經上傳好的相關檔案複製到darknet_source資料夾中(相關檔案需要自行準備)

注意cp後面所使用的格式,必須用” “將路徑包起來 同一個cell裡面,似乎不能超過6個指令

!cp "/content/gdrive/My Drive/darknet/yolov3_10000.weights" /content/darknet_source/!cp "/content/gdrive/My Drive/darknet/yolov3_bird.cfg" /content/darknet_source/cfg/!cp "/content/gdrive/My Drive/darknet/voc-bird.data" /content/darknet_source/cfg/!cp "/content/gdrive/My Drive/darknet/bird.jpg" /content/darknet_source/data/!cp "/content/gdrive/My Drive/darknet/coco.names" /content/darknet_source/data/

要記得修改data/coco.names

改成要辨識物件的名字

進行辨識

%cd /content/darknet_source!/content/darknet detect cfg/yolov3_bird.cfg yolov3_10000.weights data/bird.jpg -dont-show

觀看辨識成果

#使用OpenCV開圖片
import cv2
from google.colab.patches import cv2_imshowimg = cv2.imread('predictions.jpg', cv2.IMREAD_UNCHANGED)cv2_imshow(img)