图像项目程序

该程序实现了一个视频运动检测系统,通过OpenCV进行图像处理,检测到运动物体时触发多线程通信。主线程负责视频捕获和运动检测,子线程用于接收和发送数据。当检测到的像素点数量超过阈值时,会保存当前帧图像并记录时间。

项目程序

//// color.cpp : 定义控制台应用程序的入口点。
////
//
// vs_usb9.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include "opencv2/opencv.hpp"  
#include <iostream>    
#include<fstream>
#include <time.h>
#include <cstdlib>  
#include <windows.h>  
#include <stdlib.h>
#include<winsock.h>

#include <stdio.h>
#include <io.h>
// for fileoutput
#include <string>
#include <sstream>
#pragma comment(lib,"ws2_32.lib")



const int MAX_BUF_LEN = 255;

using namespace cv;
using namespace std;



//int bSums(Mat src)
//{
//
//	int counter = 0;
//	//迭代器访问像素点
//	Mat_<uchar>::iterator it = src.begin<uchar>();
//	Mat_<uchar>::iterator itend = src.end<uchar>();
//	for (; it != itend; ++it)
//	{
//		if ((*it) > 0) counter += 1;//二值化后,像素点是0或者255
//	}
//	return counter;
//}

//子函数声明
void initialization();
void MoveDetect(Mat temp, Mat frame);


//多线程声明
DWORD WINAPI ThreadProc2(LPVOID lpParameter);

#define MAX_LINE 1024   //定义txt中最大行数。可调整更改


int col_thread;
int con_thread;

char recvBuff[1024];
char buff[MAX_BUF_LEN]="9";


Mat frame, frame1, temp,diff,imgThresholded,hsv;  //定义矩阵


int main(int argc, char** argv)
{
	double v1,v2;
	ifstream infile;
	infile.open("D:\\9_12image\\9_12thread\\thread.txt");
	if(!infile)
		cout<<"error"<<endl;
	    string str;
		int t1;
		//cout<<"存入数组"<<endl;
	    int a[2][1];
		int*p=&a[0][0];
		while(infile>>t1)
	     {
		   *p=t1;
		   p++;
	      }
	     infile.close();
	     col_thread=a[0][0];
		con_thread=a[0][1];
	


	VideoCapture video0; 
	video0.open(0);     //读入视频 
	video0.set(CV_CAP_PROP_FRAME_WIDTH,1600);
  video0.set(CV_CAP_PROP_FRAME_HEIGHT,1200);
   

	if (!video0.isOpened())  // 如果读入失败则结束
	{
		cout << "Cannot open the web cam" << endl;
		return -1;
	}
	                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
	int i = 0; 

	while (1) { 
	
		video0 >> frame;//读帧进frame 
		imshow("frame9", frame);

		waitKey(30);
       
		if (i == 0)//如果为第一帧(temp还为空)  
		{
			MoveDetect(frame, frame);//子函数MoveDetect()进行运动物体检测,返回值存入result 
			i++;
		}
		else//若不是第一帧(temp有值了)  
		{
			MoveDetect(temp, frame);//子函数MoveDetect()进行运动物体检测,返回值存入result  
		}
		temp = frame.clone();
		memset(recvBuff,0,sizeof(recvBuff));

	}
	return 0;
}

void MoveDetect(Mat temp, Mat frame)

{
	int a=0;
	int b=0;
	frame1 = frame.clone();

	absdiff(temp, frame, diff);
	cvtColor(diff, hsv, CV_BGR2HSV);

	int counter;
	inRange(diff, Scalar(70, 70, 70), Scalar(180, 180, 180), imgThresholded);
	//int counter = bSums(imgThresholded);//调用函数bSums
	//counter=sum(sum(imgThresholded));
	//cout << "A:" << counter;
	//if (counter>=80) 
	counter = countNonZero(imgThresholded);
	if (counter >= 80)
	   {  
		  a=1;
		  b=1; 
       }
	if(b==1) //发送
	 {CreateThread(NULL, 0, ThreadProc2, NULL, 0, NULL);
	 b=0;
	 GetExitCodeThread(ThreadProc2, 0);
	  // CloseHandle(ThreadProc2);

	}
	if((a==1)||(atoi(recvBuff))) //发送与保存多线程
	{
		


		ofstream outfile;
	    outfile.open("D://9_12image//9_12position//9_position", ofstream::app);
		a=0; 
		SYSTEMTIME sys;
	    GetLocalTime(&sys);
	    char tmp[100];
	   // outfile << "position:" << "x="<<x * 0.0093+45 <<"y="<<y * 0.0375<<"   时间:" << sys.wMonth<<"月" << sys.wDay<<"日" << sys.wHour<<"时" << sys.wMinute<<"分" << sys.wSecond<<"秒" << sys.wMilliseconds<<"毫秒" << endl;
	    //保存位置更改
		IplImage *img;
		img=&IplImage(frame1);
	    sprintf(tmp, "D://共享盘//9_12image//测试//9//%d_%d_%d_%d_%d_%d.jpg",sys.wMonth,sys.wDay,sys.wHour,sys.wMinute,sys.wSecond,sys.wMilliseconds/100 );
	    //string s_file_save = tmp;
	   // cv::imwrite(s_file_save, frame1); 
		cvSaveImage(tmp, img);
        outfile.close();
	
	}
		
}


//线程1
DWORD WINAPI ThreadProc1(LPVOID lpParameter)
{	
  
	WORD wVersionRequested;
	WSADATA wsaData;//指向WinSocket信息结构的指针
	int err;

 


	// 初始化winsock库,使用socket的前提
	wVersionRequested = MAKEWORD(2, 2);
	err = WSAStartup(wVersionRequested, &wsaData);
	if(err != 0)

	{
		return -1;
	}

	if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)

	{
		WSACleanup();
		return -1;

	}


	SOCKET clientSock = socket(AF_INET, SOCK_DGRAM, 0);

	if (INVALID_SOCKET == clientSock)

	{

		err = WSAGetLastError();

		printf("socket error:%d\n", err);

		WSACleanup();

		return -1;

	}

	//创建本地地址信息并绑定

	SOCKADDR_IN sin;

	sin.sin_family = AF_INET;

	sin.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

	sin.sin_port = htons(1900);
	bool bOptval = true;
	int iret = 0; 	
	iret = setsockopt(clientSock, SOL_SOCKET, SO_REUSEADDR, (char*)&bOptval, sizeof(bOptval));	
	if (iret != 0)		
		cout << "setsockopt fail: " << WSAGetLastError() << endl;

	if (bind(clientSock, (SOCKADDR*)&sin, sizeof(sin)) != 0)

	{

		err = WSAGetLastError();

		//printf("bind error:%d\n", err);

		closesocket(clientSock);

		WSACleanup();

		return -1;

	}
	SOCKADDR_IN clientAddr;
	int addrLen = sizeof(clientAddr);
	int nSize;
	while(1){ 
		nSize = recvfrom(clientSock, recvBuff, 1024, 0, (SOCKADDR*)&clientAddr,&addrLen);
		if ( nSize == 0)
		{
			err = WSAGetLastError();
			printf("recv error:%d\n", err);
			return -1;
		}
		recvBuff[nSize] = '\0';
		printf("%s\n", recvBuff);
	}
	closesocket(clientSock);
	WSACleanup();
	return 0;
}


//线程2
DWORD WINAPI ThreadProc2(LPVOID lpParameter)
	{

	WORD wVersionRequested;

	WSADATA wasData;//指向WinSocket信息结构的指针

	int err;

 

	wVersionRequested = MAKEWORD(2, 2);

	// 初始化winsock库,使用socket的前提

	err = WSAStartup(wVersionRequested, &wasData);

	if (err != 0)

	{

		return -1;

	}

	if (LOBYTE(wasData.wVersion) != 2 || HIBYTE(wasData.wVersion) != 2)

	{

		WSACleanup();

		return -1;

	}

	SOCKET conn_sock = socket(AF_INET, SOCK_DGRAM, 0);

	if (conn_sock == INVALID_SOCKET)

	{

		err = WSAGetLastError();

		printf("socket error:%d\n", err);

		closesocket(conn_sock);

		WSACleanup();

		return -1;

	}

	bool bOpt = true;

	//打开广播选项

	setsockopt(conn_sock, SOL_SOCKET, SO_BROADCAST, (char*)&bOpt, sizeof(bOpt));

	

	// 设置发往的地址

	SOCKADDR_IN saUdpServ;

	memset(&saUdpServ, 0, sizeof(saUdpServ));

	saUdpServ.sin_family = AF_INET;

	saUdpServ.sin_addr.S_un.S_addr = htonl(INADDR_BROADCAST);

	saUdpServ.sin_port = htons(1900);

	int nSize = sizeof(SOCKADDR_IN);	
		int nSendSize = sendto(conn_sock, buff, strlen(buff), 0, (SOCKADDR*)&saUdpServ, nSize);
		if (nSendSize == SOCKET_ERROR)
		{
			err = WSAGetLastError();
			printf("sendto error:%d\n", err);
			closesocket(conn_sock);
			WSACleanup();
			return -1;
		}
		printf("send:%s\n", buff);
		Sleep(5000);
	closesocket(conn_sock);

	WSACleanup();

	return 0;

}
本资源含大量的图像处理代码(C++) int kind = 0; // 图像类型(8位kind=1,24位kind=3,初始化kind=0) LONG Bytes = 0; // 图像分配内存的最大值 BOOL Step; // 菜单上一步、下一步启动禁用标志 -> FALSE为下一步禁用 BOOL Step_All = TRUE; // 初始化上一步、下一步 -> TRUE为禁用 BOOL fdj = TRUE; // 可以使用放大镜的标志 int screen_width = GetSystemMetrics(SM_CXSCREEN); // 获取屏幕宽度 int screen_height = GetSystemMetrics(SM_CYSCREEN); // 获取屏幕高度 BOOL DirectDraw_Pause = FALSE; // DirectDraw显示时键盘中断标志 int Match_x = 0; // 模板匹配中左上方坐标 - 行 int Match_y = 0; // 模板匹配中左上方坐标 - 列 CString Match_result = ""; // 模板匹配结果 SOCKET m_socket; // 定义一个套接字 ///////////////////////////////////////////////////////////////////////////// // CMy002App initialization BOOL CMy002App::InitInstance() { // *** 判断程序是否已运行 *** HANDLE hMutex; // 定义一个句柄 // 创建一个互斥对象,并返回句柄 hMutex = CreateMutex(NULL, TRUE, "7 4 的程序"); // 主线程拥有互斥对象,相当于一次请求互斥对象 // hMutex = CreateMutex(NULL, FALSE, "7 4 的程序"); // 主线程不拥有互斥对象 // WaitForSingleObject(hMutex,INFINITE); // 请求互斥对象 if (hMutex) // 判断句柄是否有值 { if (ERROR_ALREADY_EXISTS == GetLastError()) // 判断程序是否已运行 { AfxMessageBox("该应用程序已运行! ", MB_ICONINFORMATION | MB_OK); ExitProcess(0); // 退出应用程序 } } ReleaseMutex(hMutex); // 释放互斥对象 // *** 登陆密码对话框 *** Password dlg; // 定义对话框对象 dlg.DoModal(); // 显示并运行模态对话框 - 用户登录对话框 // CG: The following block was added by the Splash Screen component. \ { \ CCommandLineInfo cmdInfo; \ ParseCommandLine(cmdInfo); \ \ C_SplashWnd::EnableSplashScreen(cmdInfo.m_bShowSplash); \ } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate( IDR_MY002TYPE, RUNTIME_CLASS(CMy002Doc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CMy002View)); AddDocTemplate(pDocTemplate); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame->LoadFrame(IDR_MAINFRAME)) return FALSE; m_pMainWnd = pMainFrame; // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // 启动时不打开子窗口 cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing; // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE; // The main window has been initialized, so show and update it. pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog // *** 关于对话框 *** { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() // App command to run the dialog void CMy002App::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // CMy002App message handlers BOOL CMy002App::PreTranslateMessage(MSG* pMsg) { // CG: The following lines were added by the Splash Screen component. if (C_SplashWnd::PreTranslateAppMessage(pMsg)) return TRUE; return CWinApp::PreTranslateMessage(pMsg); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值