基本思想:将图片传入到YOLO网络中进行识别,解析返回的信息,进行画框,写文字。
返回信息的格式:[{'label': 'dog', 'confidence': 0.87201697, 'topleft': {'x': 282, 'y': 152}, 'bottomright': {'x': 555, 'y': 509}}]
对不同信息进行提取即可得到相关信息,详情见程序。
import cv2 as cv
from darkflow.net.build import TFNet
import matplotlib.pyplot as plt
# 各个文件的地址,根据自己的路径定义,threshold为阈值,通过修改此数值可以改变识别精度,电脑没GPU的将gpu去掉即可
option = {
'model': 'cfg/yolo.cfg',
'load': 'bin/yolo.weights',
'threshold': 0.5,
'gpu': 0.7
}
tfnet = TFNet(option) # 初始化网络
img = cv.imread("dog.jpg", cv.IMREAD_COLOR) # 读取文件
# OpenCV读取图像是BGR格式的,plt显示是时候是RGB格式的,所以需要转换一下格式
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
result = tfnet.return_predict(img) # 进行预测,返回预测结果
print(result)
tl = (result[0]['topleft']['x'], result[0]['topleft']['y']) # 提取预测结果中 topleft 左上角的坐标
br = (result[0]['bottomright']['x'], result[0]['bottomright']['y']) # 提取预测结果中 bottomright 右下角的坐标
label = result[0]['label'] # 提取标签
img = cv.rectangle(img, tl, br, (0, 255, 0),