import cv2
import numpy as np
# 加载YOLOv5模型
net = cv2.dnn.readNetFromDarknet('yolov5.cfg', 'yolov5.weights')
# 获取输出层信息
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 加载图像
image = cv2.imread('image.jpg')
# 对图像进行预处理
blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)
# 将预处理后的图像输入到网络中
net.setInput(blob)
# 运行前向传播
outs = net.forward(output_layers)
# 解析输出结果
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
# 获取目标框的坐标和宽高
center_x = int(detection[0] * image.shape[1])
center_y = int(detection[1] * image.shape[0])
width = int(detection[2] * image.shape[1])
height = int(detection[3] * image.shape[0])
# 计算目标框的左上角坐标
x = int(center_x - width / 2)
y = int(center_y - height / 2)
# 保存目标框的信息
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, width, height])
# 绘制警戒区域
for box in boxes:
x, y, width, height = box
cv2.rectangle(image, (x, y), (x + width, y + height), (0, 255, 0), 2)
# 显示结果图像
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
请注意,上述代码中的yolov5.cfg和yolov5.weights是YOLOv5模型的配置文件和权重文件,需要根据实际情况进行替换。另外,image.jpg是输入图像的文件名,我们也需要将其替换为自己的图像文件。