【AI&ML】如何使用Google Colaboratory進行視頻處理

介紹

您是否知道一組計算機算法可以處理視頻流,使其能夠檢測犯罪活動,控制交通擁堵,甚至自動檢測體育廣播中的事件?由於機器學習(ML)的應用,從簡單視頻中獲取如此多數據的想法似乎並不現實。在本文中,我們希望分享我們的經驗,將機器學習算法的預構建邏輯應用於視頻的對象檢測和分割。

特別是,我們討論瞭如何配置Google Colaboratory以通過機器學習解決視頻處理任務。您將學習如何使用此Google服務及其提供的免費NVIDIA Tesla K80 GPU,以實現您在訓練神經網絡方面的目標。本文對於熟悉機器學習並考慮使用圖像識別和視頻處理的人員非常有用。

具有有限硬件資源的圖像處理

Apriorit的任務是在機器學習(ML)算法的幫助下識別視頻錄製中的人。我們決定從基礎開始。首先,讓我們考慮一下視頻錄製的實際情況。

從技術角度來看,任何視頻錄製都包含一系列以視頻編解碼器壓縮的特定格式的靜止圖像。因此,對視頻流的對象識別歸結為將流分割成單獨的圖像或幀,並將預先訓練的ML圖像識別算法應用於它們。

為此,我們決定使用Mask_R-CNN存儲庫中的神經網絡對單個圖像進行分類。存儲庫包含Python 3,TensorFlow和Keras上的卷積神經網絡的實現。讓我們看看這個計劃的結果。

Mask_RCNN示例

【AI&ML】如何使用Google Colaboratory進行視頻處理

我們開發並實現了一個簡單的樣本,Mask_RCNN它將圖片作為輸入和識別對象。我們根據Mask_R-CNN存儲庫中的demo.ipynb描述創建了一個示例。這是我們的示例代碼:

import os, sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
os.chdir("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
sys.path.append("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
# Root directory of the project
ROOT_DIR = os.path.abspath(".")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize
# Import COCO config
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version
import coco
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "images")
class InferenceConfig(coco.CocoConfig):
# Set batch size to 1 since we'll be running inference on
# one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
GPU_COUNT = 1
IMAGES_PER_GPU = 1
config = InferenceConfig()
config.display()
# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
# Load weights trained on MS-COCO
model.load_weights(COCO_MODEL_PATH, by_name=True)
# COCO Class names
# Index of the class in the list is its ID. For example, to get ID of

# the teddy bear class, use: class_names.index('teddy bear')
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']
# Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))
# Run detection
results = model.detect([image], verbose=1)
# Visualize results
r = results[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],
class_names, r['scores'])

在此示例中,/ content / drive / My Drive / Colab Notebooks / MRCNN_pure是使用Mask_R-CNN到我們的存儲庫的路徑。結果,我們得到以下結果:

【AI&ML】如何使用Google Colaboratory進行視頻處理

2019年將有創記錄的機器學習(ML)和深度學習會議,以下列表提供了即將召開的ML的會議描述,可以幫助您決定參加那個會議,贊助或者提供會談。

這部分演示代碼通過images文件夾查看,隨機選擇一個圖像,然後將其加載到我們的神經網絡模型中進行分類:

# Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))
# Run detection
results = model.detect([image], verbose=1)

讓我們修改Mask_R-CNN樣本,使其識別images文件夾中的所有圖像:

# Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
for file_name in file_names:
image = skimage.io.imread(os.path.join(IMAGE_DIR, file_name))
# Run detection
results = model.detect([image], verbose=1)
# Visualize results
r = results[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],
class_names, r['scores'])

運行演示代碼五分鐘後,控制檯顯示以下輸出:

...
Processing 1 images
image shape: (415, 640, 3) min: 0.00000 max: 255.00000 uint8
molded_images shape: (1, 1024, 1024, 3) min: -123.70000 max: 151.10000 float64
image_metas shape: (1, 93) min: 0.00000 max: 1024.00000 float64
anchors shape: (1, 261888, 4) min: -0.35390 max: 1.29134 float32

Segmentation fault (core dumped)

最初,我們在具有Intel Core i5和8GB RAM的計算機上運行演示代碼,而不使用獨立顯卡。代碼每次都在不同的地方崩潰,但最常見的是,它在內存分配期間在TensorFlow框架中崩潰。此外,在圖像識別過程中運行任何其他軟件的任何嘗試都會使計算機減慢到無用的程度。

因此,我們遇到了一個嚴重的問題:任何熟悉ML的實驗都需要強大的顯卡和更多的硬件資源。沒有這個,我們在識別大量圖像時無法執行任何其他任務。

通過Google Colaboratory增加我們的硬件資源

我們決定使用Google 的Colaboratory服務擴展我們的硬件資源,也稱為Colab。Google Colab是一款免費的雲服務,可提供CPU和GPU以及預配置的虛擬機實例。具體來說,谷歌為NVIDIA Tesla K80 GPU提供了12GB的專用視頻內存,這使得Colab成為實驗神經網絡的完美工具。

在解釋如何使用此Google服務之前,我們想強調其他有益的Colaboratory功能。

通過選擇Colab進行ML實驗,您將得到:

● 支持Python 2.7和Python 3.6,因此您可以提高編碼技能

● 能夠使用Jupyter筆記本,以便您可以創建,編輯和共享.ipynb文件

● 能夠使用本地計算機連接到Jupyter運行時

● 許多預安裝的庫,包括TensorFlow,Keras和OpenCV,以及與Google Colaboratory中的自定義庫進行交互的可能性

● 上傳功能,以便您可以添加訓練有素的模型

● 與GitHub集成,以便您可以加載公共GitHub筆記本或將Colab文件的副本保存到GitHub

● 使用像matplotlib這樣流行的庫進行簡單的可視化

● 可用於參數化代碼的表單

● 能夠將Google Colab筆記本電腦存儲在您的Google雲端硬盤中

要開始使用Google Colab GPU,您只需要提供對在Docker容器中實現的.ipynb腳本的訪問權限。Docker容器僅分配給您12個小時。您創建的所有腳本默認存儲在Colab筆記本部分的Google雲端硬盤中,該部分會在您連接到Colaboratory時自動創建。在12小時到期後,容器中的所有數據都將被刪除。您可以將Google雲端硬盤安裝到容器中並使用它來避免這種情況。否則,Docker鏡像的文件系統將僅在有限的時間段內可用。

配置Google Colab

我們首先解釋一下如何創建.ipynb筆記本。在此處打開Goog​​le Colaboratory ,選擇Google Drive部分,然後點擊NEW PYTHON 3 NOTEBOOK:

【AI&ML】如何使用Google Colaboratory進行視頻處理

通過單擊文件名重命名您的筆記本。現在您需要選擇硬件。要執行此操作,只需轉到"編輯"部分,找到"筆記本設置",選擇GPU作為硬件加速器,然後單擊"保存"保存更改。

【AI&ML】如何使用Google Colaboratory進行視頻處理

保存新設置後,將為您提供帶有獨立顯卡的Docker容器。您將在頁面右上角的" 已連接 "消息中收到有關此消息的通知:

【AI&ML】如何使用Google Colaboratory進行視頻處理

如果您沒有看到此消息,請選擇" 連接到託管運行時"。

【AI&ML】如何使用Google Colaboratory進行視頻處理

現在,您可以將Google雲端硬盤安裝到此容器,以便重新定位源代碼並將工作結果保存在容器中。要執行此操作,只需在第一個表格單元格中複製下面的代碼,然後按"播放"按鈕(或Shift + Enter)。

通過運行此代碼安裝Google雲端硬盤:

from google.colab import drive
drive.mount('/content/drive')

您將收到授權請求。單擊鏈接,授權,複製驗證碼,將其粘貼到.ipynb腳本的文本框中,然後按Enter鍵。如果授權成功,您的Google雲端硬盤將安裝在路徑/內容/驅動器/我的雲端硬盤下。要關注文件樹,請在左側菜單中選擇" 文件 "。

【AI&ML】如何使用Google Colaboratory進行視頻處理

現在您擁有一個Docker容器,其中包含Tesla K80 GPU,您的Google Drive作為文件存儲,以及.ipynb筆記本,用於執行腳本。

使用 Google Colab進行對象識別

現在我們將描述如何在Google Colab中運行Mask_R-CNN樣本以進行對象識別。我們按照/ content / drive / My Drive / Colab筆記本/路徑將Mask_RCNN存儲庫上傳到我們的Google雲端硬盤。

然後我們將示例代碼添加到.ipynb腳本中。執行此操作時,不要忘記更改您的Mask_RCNN文件夾的路徑,如下所示:

os.chdir("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
sys.path.append("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")

如果您做的一切正確,代碼執行的結果將為您提供一個圖像,其中檢測和識別所有對象。

您還可以修改示例代碼以使其處理所有測試圖像:

import os, sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
os.chdir("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
sys.path.append("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
# Root directory of the project
ROOT_DIR = os.path.abspath(".")

# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize
# Import COCO config
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version
import coco
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "images")
class InferenceConfig(coco.CocoConfig):
# Set batch size to 1 since we'll be running inference on
# one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
GPU_COUNT = 1
IMAGES_PER_GPU = 1
config = InferenceConfig()
config.display()
# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
# Load weights trained on MS-COCO
model.load_weights(COCO_MODEL_PATH, by_name=True)
# COCO Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: class_names.index('teddy bear')
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']
# Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
for file_name in file_names:
image = skimage.io.imread(os.path.join(IMAGE_DIR, file_name))

# Run detection
results = model.detect([image], verbose=1)
# Visualize results
r = results[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],
class_names, r['scores'])

使用Google Colab中的對象檢測,我們可以快速收到識別對象的結果,而我們的計算機即使在圖像識別過程中也能繼續正常運行。

使用Google Colab進行視頻處理

讓我們看看我們如何應用此方法來識別視頻流中的人物。我們將測試視頻文件上傳到Google雲端硬盤。為了訓練我們的腳本使用視頻流,我們使用了OpenCV,一種流行的開源計算機視覺庫。

我們不需要在一個圖像上讀取和實現識別模型的整個代碼。因此,而不是打開的視頻文件,我們運行的視頻流和它的指針移動到1000 個,因為沒有對象在記錄的介紹認識框架。

import cv2
...
VIDEO_STREAM = "/content/drive/My Drive/Colab Notebooks/Millery.avi"
VIDEO_STREAM_OUT = "/content/drive/My Drive/Colab Notebooks/Result.avi"
...
# initialize the video stream and pointer to output video file
vs = cv2.VideoCapture(VIDEO_STREAM)
writer = None
vs.set(cv2.CAP_PROP_POS_FRAMES, 1000);
然後我們用神經網絡模型處理20,000幀。OpenCV對象允許我們使用該read()方法從視頻文件中逐幀獲取圖像。將接收到的圖像傳遞給model.detect()方法,並使用該visualize.display_instances()函數顯示結果。

但是,我們遇到了一個問題:display_instances()Mask_RCNN存儲庫中的函數反映了圖像中檢測到的對象,但圖像沒有返回。我們決定簡化display_instances() 函數並使其返回帶有顯示對象的圖像:
def display_instances(image, boxes, masks, ids, names, scores):
"""
take the image and results and apply the mask, box, and Label
"""
n_instances = boxes.shape[0]
colors = visualize.random_colors(n_instances)
if not n_instances:
print('NO INSTANCES TO DISPLAY')
else:
assert boxes.shape[0] == masks.shape[-1] == ids.shape[0]
for i, color in enumerate(colors):
if not np.any(boxes[i]):
continue
y1, x1, y2, x2 = boxes[i]
label = names[ids[i]]
score = scores[i] if scores is not None else None
caption = '{} {:.2f}'.format(label, score) if score else label
mask = masks[:, :, i]
image = visualize.apply_mask(image, mask, color)
image = cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
image = cv2.putText(
image, caption, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 0.7, color, 2
)
return image
處理完畢後,幀應該重新綁定到一個新的視頻文件中。我們也可以使用OpenCV庫來完成此操作。我們需要做的就是VideoWriter從OpenCV庫中分配對象:
fourcc = cv2.VideoWriter_fourcc(*"XVID")
writer = cv2.VideoWriter(VIDEO_STREAM_OUT, fourcc, 30,
(masked_frame.shape[1], masked_frame.shape[0]), True)

使用我們為輸入提供的視頻類型。我們在以下幫助下獲得視頻文件類型ffprobecommand:

ffprobe Result.avi
...

Duration: N/A, start: 0.000000, bitrate: N/A
Stream #0:0: Video: mpeg4 (Simple Profile) (XVID / 0x44495658),
yuv420p, 640x272 [SAR 1:1 DAR 40:17], 30 fps, 30 tbr, 30 tbn, 30 tbc

接收的對象可用於每幀記錄:writer.write(masked_frame)。

在腳本的開頭,我們需要指定目標視頻文件的路徑以進行處理:VIDEO_STREAM和VIDEO_STREAM_OUT。

這是我們為視頻識別開發的完整腳本:

from google.colab import drive
drive.mount('/content/drive')
import os, sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
import cv2
from matplotlib.patches import Polygon
os.chdir("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
sys.path.append("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
VIDEO_STREAM = "/content/drive/My Drive/Colab Notebooks/Millery.avi"
VIDEO_STREAM_OUT = "/content/drive/My Drive/Colab Notebooks/Result.avi"
# Root directory of the project
ROOT_DIR = os.path.abspath(".")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize
# Import COCO config
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version
import coco
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
# Directory of images to run detection on

IMAGE_DIR = os.path.join(ROOT_DIR, "images")
class InferenceConfig(coco.CocoConfig):
# Set batch size to 1 since we'll be running inference on
# one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
GPU_COUNT = 1
IMAGES_PER_GPU = 1
def display_instances(image, boxes, masks, ids, names, scores):
"""
take the image and results and apply the mask, box, and Label
"""
n_instances = boxes.shape[0]
colors = visualize.random_colors(n_instances)
if not n_instances:
print('NO INSTANCES TO DISPLAY')
else:
assert boxes.shape[0] == masks.shape[-1] == ids.shape[0]
for i, color in enumerate(colors):
if not np.any(boxes[i]):
continue
y1, x1, y2, x2 = boxes[i]
label = names[ids[i]]
score = scores[i] if scores is not None else None
caption = '{} {:.2f}'.format(label, score) if score else label
mask = masks[:, :, i]
image = visualize.apply_mask(image, mask, color)
image = cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
image = cv2.putText(
image, caption, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 0.7, color, 2
)
return image
config = InferenceConfig()
config.display()
# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
# Load weights trained on MS-COCO
model.load_weights(COCO_MODEL_PATH, by_name=True)
# COCO Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: class_names.index('teddy bear')
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',

'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']
# Initialize the video stream and pointer to output video file
vs = cv2.VideoCapture(VIDEO_STREAM)
writer = None
vs.set(cv2.CAP_PROP_POS_FRAMES, 1000);
i = 0
while i < 20000:
# read the next frame from the file
(grabbed, frame) = vs.read()
i += 1
# If the frame was not grabbed, then we have reached the end
# of the stream
if not grabbed:
print ("Not grabbed.")
break;
# Run detection
results = model.detect([frame], verbose=1)
# Visualize results
r = results[0]
masked_frame = display_instances(frame, r['rois'], r['masks'], r['class_ids'],
class_names, r['scores'])
# Check if the video writer is None
if writer is None:
# Initialize our video writer
fourcc = cv2.VideoWriter_fourcc(*"XVID")
writer = cv2.VideoWriter(VIDEO_STREAM_OUT, fourcc, 30,
(masked_frame.shape[1], masked_frame.shape[0]), True)
# Write the output frame to disk
writer.write(masked_frame)
# Release the file pointers
print("[INFO] cleaning up...")
writer.release()

成功執行腳本後,帶有識別圖像的視頻文件將位於指定的路徑中VIDEO_STREAM_OUT。我們使用一部電影運行我們的系統,並接收帶有識別對象的視頻文件。看看這裡。

結論

在本文中,我們向您展示了我們如何利用Google Colab並解釋瞭如何執行以下操作:

● 使用Google Colab提供的免費Tesla K80 GPU

● 使用Mask_RCNN神經網絡和Google Colab對圖像進行分類

● 使用Mask_RCNN,Google Colab和OpenCV庫對視頻流中的對象進行分類

歡迎評論並轉發本文,關注@Ai技術聯盟,會定期推送AI專業技術知識文章,有問題可以在下面留言,小編都會回覆的,謝謝。


分享到:


相關文章: