opencv进阶-检测自定义区域

Posted 殇堼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了opencv进阶-检测自定义区域相关的知识,希望对你有一定的参考价值。

一、选区矩形区域实时显示相机视频

代码

//---------------------------------【头文件、命名空间包含部分】-----------------------------
//		描述:包含程序所使用的头文件和命名空间
//-------------------------------------------------------------------------------------------------
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
//-----------------------------------【宏定义部分】--------------------------------------------
//  描述:定义一些辅助宏 
//------------------------------------------------------------------------------------------------ 
#define WINDOW_NAME "【程序窗口】"        //为窗口标题定义的宏 


//-----------------------------------【全局函数声明部分】------------------------------------
//		描述:全局函数的声明
//------------------------------------------------------------------------------------------------
void on_MouseHandle(int event, int x, int y, int flags, void* param);    //鼠标回调函数

																		 //-----------------------------------【全局变量声明部分】-----------------------------------
																		 //		描述:全局变量的声明
																		 //-----------------------------------------------------------------------------------------------
Rect select;
bool select_flag = false, flag = true;
Point origin;
Mat org, dst, gray_image;

//-----------------------------------main( )函数】--------------------------------------------
//		描述:控制台应用程序的入口函数,我们的程序从这里开始执行
//-------------------------------------------------------------------------------------------------
int main(int argc, char** argv)
{

	VideoCapture capture(0);
	capture >> org;

	select = Rect(-1, -1, 0, 0);
	namedWindow(WINDOW_NAME);//定义一个img窗口  
	namedWindow("dst");
	setMouseCallback(WINDOW_NAME, on_MouseHandle, 0);//调用回调函数 
	while (1)
	{
		if (!capture.read(org))   //获取视频帧失败
		{
			cout << "Cannot read the frame from video file" << endl;
			break;
		}
		resize(org, org, Size(org.cols / 2, org.rows / 2), (0, 0), (0, 0), 3);
		if (flag)
		{
			flag = false;
			select = Rect(10, org.rows / 6, org.cols - 20, org.rows * 3 / 4);//第一次进入循环,记录起始点
			cout << select.x << "--" << select.y << "--" << select.width << "--" << select.height << endl;
		}
		rectangle(org, select, Scalar(255, 0, 0), 1, 8, 0);//能够实时显示在画矩形窗口时的痕迹  
		dst = org(Rect(select.x, select.y, select.width, select.height)); //将感兴趣区域复制到tmp1   
																		  //img = dst.clone();
		cvtColor(dst, gray_image, COLOR_BGR2GRAY);  //彩色图片转换成黑白图片
												 //addWeighted(dst,0.1,img,0.7,0.,dst);
		select = Rect(select.x + 10, select.y + 10, select.width - 20, select.height - 20);//记录起始点
		rectangle(org, select, Scalar(255, 0, 0), 1, 8, 0);//能够实时显示在画矩形窗口时的痕迹  
		select = Rect(select.x - 10, select.y - 10, select.width + 20, select.height + 20);//记录起始点

		rectangle(gray_image, Rect(10, 10, select.width - 20, select.height - 20), Scalar(255, 0, 0), 1, 8, 0);//能够实时显示在画矩形窗口时的痕迹  
		cout << select.x << "--" << select.y << "--" << select.width << "--" << select.height << endl;

		imshow(WINDOW_NAME, org);
		imshow("dst", gray_image);
		if (waitKey(10) == 27) break;//按下ESC键,程序退出

		waitKey(1000);
	}
	waitKey(0);
	destroyAllWindows();
	return 0;
}

//--------------------------------on_MouseHandle( )函数】-----------------------------
//		描述:鼠标回调函数,根据不同的鼠标事件进行不同的操作
//--------------------------------------------------------------------------------------
void on_MouseHandle(int event, int x, int y, int, void* param)
{
	//Point origin;//不能在这个地方进行定义,因为这是基于消息响应的函数,执行完后origin就释放了,所以达不到效果。  
	if (select_flag)
	{
		select.x = MIN(origin.x, x);//不一定要等鼠标弹起才计算矩形框,而应该在鼠标按下开始到弹起这段时间实时计算所选矩形框  
		select.y = MIN(origin.y, y);
		select.width = abs(x - origin.x);//算矩形宽度和高度  
		select.height = abs(y - origin.y);
		select &= Rect(0, 0, org.cols, org.rows);//保证所选矩形框在视频显示区域之内  
	}
	if (event == EVENT_LBUTTONDOWN)
	{
		select_flag = true;//鼠标按下的标志赋真值  
		origin = Point(x, y);//保存下来单击是捕捉到的点  
		select = Rect(x, y, 0, 0);//这里一定要初始化,宽和高为(0,0)是因为在opencvRect矩形框类内的点是包含左上角那个点的,但是不含右下角那个点 
	}
	else if (event == EVENT_LBUTTONUP)
	{
		select_flag = false;
	}
}

二、检测特定区域内的物体

//---------------------------------【头文件、命名空间包含部分】-----------------------------
//		描述:包含程序所使用的头文件和命名空间
//-------------------------------------------------------------------------------------------------
#include <opencv2\\opencv.hpp>
#include <opencv2\\dnn.hpp>
#include <iostream>

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

const size_t width = 300;
const size_t height = 300;
const float meanVal = 127.5;
const float scaleFactor = 0.007843f;
const char* classNames[] = { "background",
"aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair",
"cow", "diningtable", "dog", "horse",
"motorbike", "person", "pottedplant",
"sheep", "sofa", "train", "tvmonitor" };

String labelFile = "D:/opencv-4.1.0/models/ssd/labelmap_det.txt";
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";
//-----------------------------------【宏定义部分】--------------------------------------------
//  描述:定义一些辅助宏 
//------------------------------------------------------------------------------------------------ 
#define WINDOW_NAME "【程序窗口】"        //为窗口标题定义的宏 

//-----------------------------------【全局函数声明部分】------------------------------------
//		描述:全局函数的声明
//------------------------------------------------------------------------------------------------

void on_MouseHandle(int event, int x, int y, int flags, void* param);    //鼠标回调函数
 //-----------------------------------【全局变量声明部分】-----------------------------------
//		描述:全局变量的声明
 //-----------------------------------------------------------------------------------------------
Rect select;
bool select_flag = false, flag = true;
Point origin;
Mat org, frame, gray_image, binary_image;

//-----------------------------------main( )函数】--------------------------------------------
//		描述:控制台应用程序的入口函数,我们的程序从这里开始执行
//-------------------------------------------------------------------------------------------------
int main(int argc, char** argv)
{
	VideoCapture capture(0);
	capture >> org;
	Net net = readNetFromCaffe(model_text_file, modelFile);
	select = Rect(-1, -1, 0, 0);
	namedWindow(WINDOW_NAME);//定义一个img窗口  
	namedWindow("dst");
	setMouseCallback(WINDOW_NAME, on_MouseHandle, 0);//调用回调函数 

	while (1)
	{
		if (!capture.read(org))   //获取视频帧失败
		{
			cout << "Cannot read the frame from video file" << endl;
			break;
		}

		if (flag)
		{
			flag = false;
			select = Rect(10, org.rows / 6, org.cols - 20, org.rows * 3 / 4);//第一次进入循环,记录起始点
			cout << select.x << "--" << select.y << "--" << select.width << "--" << select.height << endl;
		}
		rectangle(org, select, Scalar(255, 0, 0), 1, 8, 0);//能够实时显示在画矩形窗口时的痕迹  
		frame = org(Rect(select.x, select.y, select.width, select.height)); //将感兴趣区域复制到tmp1   
																
		Mat inputblob = blobFromImage(frame, scaleFactor, Size(width, height), meanVal, false);
		net.setInput(inputblob, "data");
		net.setPreferableBackend(DNN_BACKEND_OPENCV);
		net.setPreferableTarget(DNN_TARGET_CPU);
		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", classNames[objIndex], confidence), Point(tl_x, tl_y), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(255, 0, 0), 2);
			}
		}
		vector < double>layerstimings;
		double freq = getTickFrequency() / 1000;
		double tim

以上是关于opencv进阶-检测自定义区域的主要内容,如果未能解决你的问题,请参考以下文章

opencv进阶-基于coco数据集训练好的模型,修改类别显示代码,实现自定义检测物体

opencv进阶-基于coco数据集训练好的模型,修改类别显示代码,实现自定义检测物体

opencv进阶-自定义对象检测

opencv进阶-YOLOv4检测交通标志

opencv进阶-YOLOv4检测交通标志

人脸检测进阶:使用 dlibOpenCV 和 Python 检测眼睛鼻子嘴唇和下巴等面部五官