目录
1. OpenCV
这里我们用YOLOv3COCO的模型来给照片做检测。我们用tensornets导入预训练的YOLO模型,用OpenCV给照片添加方框和文字,用matplotlib显示图片。
tensornets提供对各种预训练模型的高层接口,包括YOLOv2、YOLOv3、Faster RCNN。
OpenCV中的cv2.rectangle和cv2.putText两个函数分别给图片添加方框和文字。请点击超链接查看两个函数的文档。
我们输入这样的图片
用下面这些代码处理上图。
import tensorflow as tf
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import cv2 as cv
import tensornets as nets
from tensornets.datasets.coco import classnames
# 输入占位符
input_img = tf.placeholder(shape=(None, 416, 416, 3), dtype=tf.float32)
# 实例化YOLO模型
yolov3 = nets.YOLOv3COCO(input_img)
img_path = './road.bmp'
# 读入图片
image = Image.open(img_path)
# 放缩图片到指定大小
image_resize = image.resize((416, 416))
image_resize = np.expand_dims(np.asarray(image_resize), 0)
# TensorFlow的配置
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
# 运行YOLO模型获得各个物体类别的方框及其可信度
with tf.Session(config=config) as sess:
sess.run(yolov3.pretrained())
res = sess.run(yolo