注意:我用的代码不是YOLO官方的源代码
如果你已经用了YOLO官方的源代码--就不用看了
如果你还没有Yolo代码可以参考一下
一、代码
二、修改的地方
具体如何使用、预测、训练等看博主的视频讲解
都有
位于 yolo.py里面
#---------------------------------------------------------#
# 图像绘制
#---------------------------------------------------------#
number = 0
for i, c in list(enumerate(top_label)):
predicted_class = self.class_names[int(c)]
box = top_boxes[i]
score = top_conf[i]
top, left, bottom, right = box
top = max(0, np.floor(top).astype('int32'))
left = max(0, np.floor(left).astype('int32'))
bottom = min(image.size[1], np.floor(bottom).astype('int32'))
right = min(image.size[0], np.floor(right).astype('int32'))
label = '{} {:.2f}'.format(predicted_class, score)
draw = ImageDraw.Draw(image)
label_size = draw.textsize(label, font)
label = label.encode('utf-8')
#print("预测框数据:",label, top, left, bottom, right)
if top - label_size[1] >= 0:
text_origin = np.array([left, top - label_size[1]])
else:
text_origin = np.array([left, top + 1])
for i in range(thickness):
draw.rectangle([left + i, top + i, right - i, bottom - i], outline=self.colors[c])
draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)], fill=self.colors[c])
draw.text(text_origin, str(label,'UTF-8'), fill=(0, 0, 0), font=font)
del draw
-------------------------------------以下是添加的----------------------------------------------
# ---------------------------------------------------------#
# 区域检测
# ---------------------------------------------------------#
# 预测框中心点
x = (left + right) // 2
y = (top + bottom) // 2
centre = (x, y)
#print("预测框中心点:", centre)
b = ImageDraw.ImageDraw(image) # 用b来表示
b.point(centre, fill='blue')
# 绘制区域---------检测区域自行修改
h = image_shape[1] # 图片的长
k = image_shape[0] # 图片的宽
x1 = h // 10 # 左 # 左上角x值=长的1/10
x2 = (9 * h) // 10 # 右 # 右上角x值=长的9/10
y1 = k // 10 # 上 # 左上角y值=长的1/10
y2 = (9 * k) // 10 # 下 # 右上角y值=长的9/10
a = ImageDraw.ImageDraw(image) # 用a来表示
a.rectangle(((x1, y1), (x2, y2)), fill=None, outline='green', width=5)
# 判断中心点是否在区域内
'''
判断x的值是否在范围内
判断y值是否在范围内
'''
# 判断x值
if x in range(x1, (x2 + 1)):
if y in range(y1, (y2 + 1)):
number += 1
else:
break
else:
break
print("警告!有人入侵!!!")
print('人数:', number)
num = str(number)
d = ImageDraw.ImageDraw(image) # 用d来表示
d.text((5, 10), "人数:" + num, fill=(255, 0, 0), font=font) # 左上角显示人数
----------------------------------------以上-------------------------------------------------
return image
修改后预测就行了(视频、图片都可以)