opencv 调用 YOLOv3 进行目标检测

训练好的模型参数可以在这个脚本文件中找到,这是针对 coco 数据集训练得到的目标检测网络。 Common Objects in COntext 数据集是微软发布的一个大型图像数据集, 专为对象检测、分割、人体关键点检测、语义分割和字幕生成而设计。数据集中的目标种类有 80 个。
https://github.com/spmallick/learnopencv/blob/master/ObjectDetection-YOLO/getModels.sh

# 这是获取模型参数的 shell 脚本,也可以直接在浏览器下载
wget https://pjreddie.com/media/files/yolov3.weights
wget https://github.com/pjreddie/darknet/blob/master/cfg/yolov3.cfg?raw=true -O ./yolov3.cfg
wget https://github.com/pjreddie/darknet/blob/master/data/coco.names?raw=true -O ./coco.names
'''
YOLO demo
'''
COLORS = [(255,0,0) for i in range(80)]    # 这里所有种类都用蓝色,可以给不同种类用不同颜色
with open('yolo/coco.names','r') as file:     # 这是读取所有种类的名字
	LABELS = file.read().splitlines()

args = {
    "yolo": "yolo",   #.weights 和 .cfg 文件所在的目录
    "image": "animals.jpg",
    "confidence": 0.1,              # minimum bounding box confidence
    "threshold": 0.3,               # NMS threshold
}

# derive the paths to the YOLO weights and model configuration
weightsPath = os.path.sep.join([args["yolo"], "yolov3.weights"])
configPath = os.path.sep.join([args["yolo"], "yolov3.cfg"])
 
# load YOLO object detector trained on COCO dataset (80 classes)
print("[INFO] loading YOLO from disk...")
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)

# load our input image and grab its spatial dimensions
image = cv2.imread(args["image"])
(H, W) = image.shape[:2]
 
# determine only the *output* layer names that we need from YOLO
ln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]

# construct a blob from the input image and then perform a forward
# pass of the YOLO object detector, giving us our bounding boxes and
# associated probabilities
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416),
	swapRB=True, crop=False)
net.setInput(blob)
start = time.time()
layerOutputs = net.forward(ln)
end = time.time()
 
# show timing information on YOLO
print("[INFO] YOLO took {:.6f} seconds".format(end - start))

boxes, confidences, classIDs = [], [], []
# loop over each of the layer outputs
for output in layerOutputs:
	# loop over each of the detections
	for detection in output:
		# extract the class ID and confidence of the current object detection
		scores = detection[5:]
		classID = np.argmax(scores)
		confidence = scores[classID]
 
		# filter out weak predictions by ensuring the detected
		# probability is greater than the minimum probability
		if confidence > args["confidence"]:
			# scale the bounding box coordinates back relative to the size of the image, 
            # keeping in mind that YOLO actually returns the center (x, y)-coordinates 
            # of the bounding box followed by the boxes' width and height
			box = detection[0:4] * np.array([W, H, W, H])
			(centerX, centerY, width, height) = box.astype("int")
 
			# use the center (x, y)-coordinates to derive the top and left corner of the bounding box
			x = int(centerX - (width / 2))
			y = int(centerY - (height / 2))
 
			# update our list of bounding box coordinates, confidences, and class IDs
			boxes.append([x, y, int(width), int(height)])
			confidences.append(float(confidence))
			classIDs.append(classID)

idxs = cv2.dnn.NMSBoxes(boxes, confidences, args["confidence"],
	args["threshold"])

# ensure at least one detection exists
if len(idxs) > 0:
	# loop over the indexes we are keeping
	for i in idxs.flatten():
		# extract the bounding box coordinates
		(x, y) = (boxes[i][0], boxes[i][1])
		(w, h) = (boxes[i][2], boxes[i][3])
 
		# draw a bounding box rectangle and label on the image
		color = [int(c) for c in COLORS[classIDs[i]]]
		cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
		text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
		cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,
			0.5, color, 2)
 
# show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)

结果如下,图片是从网上随便找来的:
在这里插入图片描述

[INFO] loading YOLO from disk...
[INFO] YOLO took 0.996802 seconds
### 回答1: 要使用OpenCV调用Yolov5目标识别,需要先安装OpenCVYolov5。然后,可以使用OpenCV的cv::dnn模块来加载Yolov5模型,并使用它来检测图像中的目标。具体步骤如下: 1. 安装OpenCVYolov5。 2. 下载Yolov5预训练模型权重文件和配置文件。 3. 使用OpenCV的cv::dnn模块加载Yolov5模型。可以使用以下代码: cv::dnn::Net net = cv::dnn::readNetFromDarknet("yolov5.cfg", "yolov5.weights"); 4. 加载图像并将其转换为OpenCV的Mat格式。 5. 将Mat格式的图像传递给Yolov5模型进行目标检测。可以使用以下代码: cv::Mat inputBlob = cv::dnn::blobFromImage(image, 1 / 255., cv::Size(416, 416), cv::Scalar(, , ), true, false); net.setInput(inputBlob); cv::Mat detectionMat = net.forward(); 6. 解析检测结果并在图像上绘制检测框。可以使用以下代码: float* data = (float*)detectionMat.data; for (int i = ; i < detectionMat.rows; i++, data += detectionMat.cols) { cv::Mat scores = detectionMat.row(i).colRange(5, detectionMat.cols); cv::Point classIdPoint; double confidence; cv::minMaxLoc(scores, , &confidence, , &classIdPoint); if (confidence > confidenceThreshold) { int centerX = (int)(data[] * image.cols); int centerY = (int)(data[1] * image.rows); int width = (int)(data[2] * image.cols); int height = (int)(data[3] * image.rows); int left = centerX - width / 2; int top = centerY - height / 2; cv::rectangle(image, cv::Rect(left, top, width, height), cv::Scalar(, 255, ), 2); } } 7. 显示图像并等待用户按下任意键退出。可以使用以下代码: cv::imshow("Yolov5 Object Detection", image); cv::waitKey(); 以上就是使用OpenCV调用Yolov5目标识别的基本步骤。需要注意的是,Yolov5模型的输入图像大小为416x416,因此需要将输入图像缩放到该大小。另外,需要设置置信度阈值来过滤低置信度的检测结果。 ### 回答2: Opencv是一个流行的计算机视觉库,它可以用来实现各种图像处理和计算机视觉应用,比如目标识别、物体跟踪、人脸识别等。而Yolov5则是一种基于深度学习的目标检测算法,它可以用来识别图像中的各种物体,并将它们标注出来。下面我们来介绍一下如何使用Opencv调用Yolov5进行目标识别。 首先,我们需要安装Yolov5和Opencv的相关库文件。Yolov5可以直接通过Github的仓库获取,而Opencv可以通过pip命令进行安装,安装完成后我们需要在Python中导入这些库文件。 ``` python import cv2 from matplotlib import pyplot as plt from numpy import random import torch import torch.backends.cudnn as cudnn #导入Yolov5模型的‘detect'函数 from yolov5.models.experimental import attempt_load from yolov5.utils.general import non_max_suppression from yolov5.utils.datasets import letterbox from yolov5.utils.plots import plot_one_box ``` 接下来,我们需要加载训练好的Yolov5模型,以及设置一些模型参数。 ``` python # 指定设备 device = 'cpu' # 这里如果有GPU可用,建议使用GPU,否则多张图片进行推断速度会很慢 weights_path = "C:/Users/*****/yolov5/weights/yolov5m.pt" # 训练好的模型权重地址 img_size = 640 # 输入图片的大小 conf_thres = 0.5 # 目标置信度阈值 iou_thres = 0.4 # NMS的IOU阈值 augment = False # 图像增强 view_img = False # 视觉化推断的结果 save_txt = False # 是否保存结果的txt文件 save_conf = False # 是否输出每个目标的置信度 ``` 然后,我们需要加载输入图片,并将其转换为Yolov5模型所需的格式。 ``` python # 使用Opencv加载图片 img_path = "C:/Users/*****/yolov5/data/images/test.jpg" img = cv2.imread(img_path) # 将图像转换为RGB格式 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 对图像进行缩放和填充,使其符合Yolov5模型输入要求 img = letterbox(img, img_size, 32)[0] # 将图像转换为Tensor格式,并添加一个批次维度 img = torch.from_numpy(img).to(device) img = img.unsqueeze(0).float() ``` 接下来,我们可以使用Yolov5模型的“detect”函数进行目标识别了,这个函数会返回检测到的目标信息。 ``` python # 加载Yolov5模型 model = attempt_load(weights_path, map_location=device) # 模型加载 # 将模型设置为推断模式 model.eval() # 设置GPU加速 if device == 'cuda': cudnn.benchmark = True model.cuda() with torch.no_grad(): # 将图像传入模型 detections = model(img) # 对模型的输出进行NMS处理 detections = non_max_suppression(detections, conf_thres=conf_thres, iou_thres=iou_thres) ``` 最后,我们可以将检测到的目标信息绘制到输入图片上,以便可视化识别结果。 ``` python # 将检测结果可视化 if detections is not None: for detection in detections: if save_txt: # 将目标框的信息保存到txt文件中 with open(txt_path + 'det.txt', mode='a') as file: file.write( '%g %g %g %g %g %g\n' % ( detection[0], detection[1], detection[2], detection[3], detection[4], detection[5])) # 按类别绘制目标框和置信度 colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(detection))] for i, det in enumerate(detection): # detections per image plot_one_box( det[:4], img, label='%.2f' % det[4], color=colors[i], line_thickness=3) if view_img: # 将结果显示在窗口中 plt.imshow(img) plt.show() ``` 综上所述,通过以上步骤,我们可以使用Opencv调用Yolov5进行目标识别,实现对图像中物体的检测和识别。同时,由于Yolov5模型具有较高的检测精度和速度,因此在实际应用中也有着广泛的应用前景。 ### 回答3: OpenCV是一种开源的计算机视觉库,支持图像和视频的处理、深度学习、目标识别、跟踪等功能,而yolov5则是一种高效的目标检测模型,由ultralytics公司研发,目前已成为业界广泛使用的目标识别工具之一。在使用OpenCV进行目标识别时,可以结合yolov5进行更准确、高效的检测。 接下来介绍如何使用OpenCV调用yolov5进行目标识别。 1. 安装OpenCVyolov5 首先,需要安装OpenCVyolov5。可以使用pip命令快速安装,也可以从源码进行编译安装。在安装OpenCV时需要注意,需要安装OpenCV的深度学习模块,以便于后续调用yolov5。 2. 定义yolov5模型 在进行目标识别前,需要定义yolov5模型。可以使用官方提供的预训练模型,也可以根据自己的数据进行训练得到模型。在使用模型前,需要将模型加载到内存中,并定义好输入和输出层。 3. 调用OpenCV进行目标识别 接下来,可以调用OpenCV对图像进行目标识别。首先需要读取图像,然后将图像进行预处理,包括缩放、裁剪、归一化等操作,以便于输入到yolov5模型进行检测。检测完成后,可以得到检测结果,包括目标类别、位置、置信度等信息,可以根据需求进行后续处理,比如绘制检测框、标注类别等。 以上就是使用OpenCV调用yolov5进行目标识别的基本流程。需要注意的是,yolov5是一种较为复杂的模型,运行时需要较大的计算资源,建议在较为高配置的机器上进行模型的训练和调用。同时,在使用yolov5时也需要注意模型参数的选择和调整,以便于得到更准确、高效的检测结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值