【OpenCV进阶】如何基于SSD模型实现对物体的实时检测

📢:如果你也对机器人、人工智能感兴趣,看来我们志同道合✨
📢:不妨浏览一下我的博客主页【https://blog.csdn.net/weixin_51244852
📢:文章若有幸对你有帮助,可点赞 👍 收藏 ⭐不迷路🙉
📢:内容若有错误,敬请留言 📝指正!原创文,转载注明出处

在这里插入图片描述

引言

reference:利用OpenCV和深度学习实现人脸检测
2018年之后,opencv DNN模式下开始使用卷积神经网络SSD人脸检测器,目前商业应用非常成熟,可以做到实时运行,对各种角度人脸均能做到准确的检测,具有很强的抗干扰性。

注意:opencv自带的人脸检测模型

一、安装Opencv

Opencv学习-第1节:环境配置与搭建

二、下载模型文件

打开windows下的终端,点击左下角的徽标键,输入cmd即可。然后在终端输入cd /d D:\opencv-4.1.0\opencv\sources\samples\dnn\face_detector
然后继续输入:python download_weights.py,这样就会根据权重文件生成配置文件和模型文件。

三、查看参数

进入models.yml文件,查看需要设置的参数。文件路径:D:\opencv-4.1.0\opencv\sources\samples\dnn
在这里插入图片描述

全部代码

1.基于caffe

基于caffe框架下的SSD深度卷积神经网络模型,做人脸检测。
.prototxt和.caffemodel的作用如下:

The .prototxt file(s) which define the model architecture (i.e., the layers themselves)

The .caffemodel file which contains the weights for the actual layers

#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>

using namespace cv;
using namespace cv::dnn;
using namespace std;

String model_text_file = "D:/opencv-4.1.0/models/face_detector/deploy.prototxt";
String modelFile = "D:/opencv-4.1.0/models/face_detector/res10_300x300_ssd_iter_140000_fp16.caffemodel";

int main(int argc, char** argv) {
	VideoCapture capture;
	capture.open(0);
	namedWindow("input", WINDOW_AUTOSIZE);
	int w = capture.get(CAP_PROP_FRAME_WIDTH);
	int h = capture.get(CAP_PROP_FRAME_HEIGHT);
	printf("frame width : %d, frame height : %d", w, h);

	// set up net
	Net net = readNetFromCaffe(model_text_file, modelFile);
	net.setPreferableBackend(DNN_BACKEND_OPENCV);
	net.setPreferableTarget(DNN_TARGET_CPU);

	Mat frame;
	while (capture.read(frame)) {
		flip(frame, frame, 1);
		imshow("input", frame);

		//预测
		Mat inputblob = blobFromImage(frame, 1.0, Size(300, 300), Scalar(104,177,123), false);
		net.setInput(inputblob, "data");
		Mat detection = net.forward("detection_out");

		//检测
		Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>());
		float confidence_threshold = 0.25;
		for (int i = 0; i < detectionMat.rows; i++) {
			float confidence = detectionMat.at<float>(i, 2);
			if (confidence > confidence_threshold) {
				size_t objIndex = (size_t)(detectionMat.at<float>(i, 1));
				float tl_x = detectionMat.at<float>(i, 3) * frame.cols;
				float tl_y = detectionMat.at<float>(i, 4) * frame.rows;
				float br_x = detectionMat.at<float>(i, 5) * frame.cols;
				float br_y = detectionMat.at<float>(i, 6) * frame.rows;

				Rect object_box((int)tl_x, (int)tl_y, (int)(br_x - tl_x), (int)(br_y - tl_y));
				rectangle(frame, object_box, Scalar(0, 0, 255), 2, 8, 0);
				putText(frame, format("%s %.2f", "face", confidence), Point(tl_x, tl_y), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(255, 0, 0), 2);
			}
		}
		vector < double>layerstimings;
		double freq = getTickFrequency() / 1000;
		double time = net.getPerfProfile(layerstimings) / freq;
		ostringstream ss;
		ss << "FPS" << 1000 / time << ";time:" << time << "ms";
		putText(frame, ss.str(), Point(20, 20), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255), 2, 8);
		imshow("face-detection-demo", frame);
		char c = waitKey(5);
		if (c == 27) { // ESC退出
			break;
		}
	}
	capture.release();//释放资源
	waitKey(0);
	return 0;
}

2.基于TensorFlow

基于TensorFlow的SSD模型,人脸检测。

#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>

using namespace cv;
using namespace cv::dnn;
using namespace std;

String model_text_file = "D:/opencv-4.1.0/models/face_detector/opencv_face_detector.pbtxt";
String modelFile = "D:/opencv-4.1.0/models/face_detector/opencv_face_detector_uint8.pb";

int main(int argc, char** argv) {
	VideoCapture capture;
	capture.open(0);
	namedWindow("input", WINDOW_AUTOSIZE);
	int w = capture.get(CAP_PROP_FRAME_WIDTH);
	int h = capture.get(CAP_PROP_FRAME_HEIGHT);
	printf("frame width : %d, frame height : %d", w, h);

	// set up net
	Net net = readNetFromTensorflow(modelFile, model_text_file);

	net.setPreferableBackend(DNN_BACKEND_OPENCV);
	net.setPreferableTarget(DNN_TARGET_CPU);

	Mat frame;
	while (capture.read(frame)) {
		flip(frame, frame, 1);
		imshow("input", frame);

		//预测
		Mat inputblob = blobFromImage(frame, 1.0, Size(300, 300), Scalar(104,177,123), false);
		net.setInput(inputblob, "data");
		Mat detection = net.forward("detection_out");

		//检测
		Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>());
		float confidence_threshold = 0.25;
		for (int i = 0; i < detectionMat.rows; i++) {
			float confidence = detectionMat.at<float>(i, 2);
			if (confidence > confidence_threshold) {
				size_t objIndex = (size_t)(detectionMat.at<float>(i, 1));
				float tl_x = detectionMat.at<float>(i, 3) * frame.cols;
				float tl_y = detectionMat.at<float>(i, 4) * frame.rows;
				float br_x = detectionMat.at<float>(i, 5) * frame.cols;
				float br_y = detectionMat.at<float>(i, 6) * frame.rows;

				Rect object_box((int)tl_x, (int)tl_y, (int)(br_x - tl_x), (int)(br_y - tl_y));
				rectangle(frame, object_box, Scalar(0, 0, 255), 2, 8, 0);
				putText(frame, format("%s %.2f", "face", confidence), Point(tl_x, tl_y), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(255, 0, 0), 2);
			}
		}
		vector < double>layerstimings;
		double freq = getTickFrequency() / 1000;
		double time = net.getPerfProfile(layerstimings) / freq;
		ostringstream ss;
		ss << "FPS" << 1000 / time << ";time:" << time << "ms";
		putText(frame, ss.str(), Point(20, 20), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255), 2, 8);
		imshow("face-detection-demo", frame);
		char c = waitKey(5);
		if (c == 27) { // ESC退出
			break;
		}
	}
	capture.release();//释放资源
	waitKey(0);
	return 0;
}

3.效果展示

在笔记本上运行,还挺流程的。
在这里插入图片描述

SSD模型-物体检测

全部代码

#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>

using namespace cv;
using namespace cv::dnn;
using namespace std;

String model_text_file = "D:/opencv-4.1.0/models/ssd/MobileNetSSD_deploy.prototxt";
String modelFile = "D:/opencv-4.1.0/models/ssd/MobileNetSSD_deploy.caffemodel";

String objNames[] = { "background","aeroplane", "bicycle", "bird", "boat","bottle", "bus", "car", "cat", "chair","cow", "diningtable", "dog", "horse","motorbike", "person", "pottedplant","sheep", "sofa", "train", "tvmonitor" };//只检测20种对象

int main() {
	Mat src = imread("D:/images/objects.jpg");
	if (src.empty()) {
		printf("could not load image...\n");
		return -1;
	}
	imshow("input image", src);

	Net net = readNetFromCaffe(model_text_file, modelFile);

	//构建输入
	Mat blobImage = blobFromImage(src, 0.007843,Size(300, 300),Scalar(127.5, 127.5, 127.5), true, false);
	printf("blobImage width : %d, height: %d\n", blobImage.cols, blobImage.rows);
	net.setInput(blobImage, "data");
		
	//执行推理
	Mat detection = net.forward("detection_out");
	Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>());
	float confidence_threshold = 0.2;

	//解析输出数据
	for (int i = 0; i < detectionMat.rows; i++) {
		float confidence = detectionMat.at<float>(i, 2);
		if (confidence > confidence_threshold) {
			size_t objIndex = (size_t)(detectionMat.at<float>(i, 1));
			float tl_x = detectionMat.at<float>(i, 3) * src.cols;
			float tl_y = detectionMat.at<float>(i, 4) * src.rows;
			float br_x = detectionMat.at<float>(i, 5) * src.cols;
			float br_y = detectionMat.at<float>(i, 6) *src.rows;

			Rect object_box((int)tl_x, (int)tl_y, (int)(br_x - tl_x), (int)(br_y - tl_y));
			rectangle(src, object_box, Scalar(0, 0, 255), 2, 8, 0);
			putText(src, format("%.2f,%s", confidence, objNames[objIndex].c_str()), Point(tl_x, tl_y), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 0, 0), 2);
		}
	}
	imshow("ssd-demo",src);

	waitKey(0);
	return 0;
}

效果展示

在这里插入图片描述

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
### 回答1: 在使用Qt和OpenCV实现基于颜色的物体区分时,可以按照以下步骤进行操作: 1. 导入Qt和OpenCV的相关库和头文件。 2. 打开摄像头或者读取视频为输入源。 3. 读取每一帧图像。 4. 将图像从BGR色彩空间转换为HSV色彩空间,由于HSV色彩空间更适合进行颜色分析。 5. 设定目标物体的颜色范围,使用inRange函数进行颜色分割,得到目标物体的二值图像。 6. 对二值图像进行形态学操作,如腐蚀和膨胀,以消除噪声和填充目标物体内部空洞。 7. 使用findContours函数找到目标物体的轮廓。 8. 根据轮廓的特征,如面积、周长、外接矩形等,对目标物体进行筛选,去除不符合条件的轮廓。 9. 在原始图像上绘制出符合条件的目标物体轮廓。 10. 可以选择添加其他附加功能,如标记目标物体的中心点、显示物体跟踪trajectory等。 11. 循环执行步骤3至步骤10,实现实时的基于颜色的物体区分。 12. 释放摄像头或关闭视频文件。 13. 结束程序运行。 通过以上步骤,可以利用Qt和OpenCV实现基于颜色的物体区分,通过对目标物体颜色的提取和轮廓分析,实现对不同颜色物体的识别和分割。 ### 回答2: Qt是一种跨平台的应用程序框架,而OpenCV是一个功能强大的开源计算机视觉库。结合Qt和OpenCV,我们可以实现基于颜色的物体区分。 首先,要使用Qt和OpenCV,在Qt项目中包括OpenCV库并链接到项目中。接下来,我们需要通过Qt提供的界面来获取图像。可以使用Qt的QCamera类来连接到摄像头并捕获实时图像,或者使用Qt的QFileDialog类来选择所需的图像文件。 一旦我们获得了图像,我们就可以使用OpenCV的函数进行图像处理和分析。对于基于颜色的物体区分,首先需要将图像从RGB颜色空间转换为HSV颜色空间。在HSV颜色空间中,我们可以更容易地对颜色进行分析。 然后,我们可以根据所需颜色的HSV范围来创建一个掩码。掩码是一个二进制图像,其中白色像素表示在指定颜色范围内的像素,而黑色像素表示不在范围内的像素。我们可以使用OpenCV的inRange函数创建此掩码。 接下来,我们可以使用掩码将原始图像中的物体分割出来。可以使用OpenCV的bitwise_and函数将原始图像与掩码进行按位与操作,从而只保留掩码中的白色区域。 最后,我们可以在Qt界面中显示分割出的物体。可以使用Qt的QPixmap类将OpenCV的Mat对象转换为Qt的QImage对象并显示在Qt的窗口上。 总结起来,使用Qt和OpenCV实现基于颜色的物体区分将涉及连接到摄像头或选择图像文件,将图像从RGB转换为HSV颜色空间,创建颜色范围掩码,使用掩码分割图像和在Qt界面中显示结果。 ### 回答3: Qt与OpenCV结合可以实现基于颜色的物体区分。首先,我们需要使用Qt框架实现图像的读取和显示功能。通过Qt的图片处理类,我们可以方便地读取和显示图片。 然后,我们集成OpenCV库,通过Qt的信号和槽机制与OpenCV库进行交互。使用OpenCV库的颜色空间转换函数,我们可以将图片转换为HSV色彩空间。HSV色彩空间相对于RGB色彩空间更适合颜色分析。 接下来,我们可以使用OpenCV库的阈值函数来分割图像中的不同颜色区域。通过设置合适的阈值,我们可以将目标物体的颜色从背景中区分出来。之后,我们可以通过OpenCV库的形态学操作对图像进行进一步处理,如腐蚀和膨胀,以消除噪声和填充空洞。 最后,使用Qt的绘图功能,我们可以在原始图像上绘制标记框或者轮廓,以展示区分出的目标物体。同时,可以利用Qt的界面设计功能,添加一些按钮和滑动条等控件,以便用户可以交互式地调整参数,实时观察效果。 总之,通过Qt的图像处理OpenCV的颜色分割技术,我们可以实现基于颜色的物体区分。这样的系统可以应用于许多领域,如机器人视觉、工业自动化等。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嵌小超

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值