【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专业技术知识文章,有问题可以在下面留言,小编都会回复的,谢谢。


分享到:


相關文章: