-
Notifications
You must be signed in to change notification settings - Fork 0
/
workerThread.cpp
500 lines (423 loc) · 14.2 KB
/
workerThread.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//#include <opencv2\opencv.hpp>
//#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <ctime>
#include <cmath>
#include <process.h>
#include <fstream> // for fstream open file
#include <direct.h> //get current working directory _getcwd
//#include <Windows.h>
#include "workerThread.h"
//ãªéàËÁ×͹¡Ñ¹ ·Ñé§ workerThread áÅÐ Option form
#define MAXSIZE 500
#define DEFAULT_STRING_SIZE 256
char g_INI_FName[]="\\\\apm.ini";
#pragma comment(lib, "User32.lib")
namespace APM {
using namespace std;
using namespace cv;
using namespace System;
using namespace System::Windows::Forms;
workerThread::workerThread(void)
{
m_shouldStop = false;
m_iCapEveryNSec =180;// time (second) to detect motion every X (second).µÃǨ¨Ñº¤ÇÒÁà»ÅÕè¹á»Å§·Ø¡ X s 1- max integer
m_iThresDiff= 50; //¤èÒÊÕµèÒ§¡Ñ¹ (˹èÇÂ) ¶×ÍÇèÒà»ç¹¡ÒÃà¤Å×è͹äËÇ 0-255
m_iThresShutdownComputer= 300; //ËÒ¡Áըӹǹ pixel ·ÕèÁÕ¡ÒÃà¤Å×è͹äËǵèÓ¡ÇèҨРshutdown 0-307200
m_iThresBootComputer=1000; // 0-307200
m_iNumberOfDelay= 100;// àÇÅÒ˹èǧ (ÇÔ¹Ò·Õ) 㹡Òà start ¡Åéͧ webcam 0- max integer
m_strIniFileName = NULL;
m_strIniFileName = new char[MAXSIZE];
//-------------------------------------------
//read data from ini file
char buf[DEFAULT_STRING_SIZE];
// char strpath[DEFAULT_STRING_SIZE];
// int retVal = 0;
// unsigned short pathStrLen;//,iniStrLen;
char* pstr;
if( _getcwd(buf, DEFAULT_STRING_SIZE) ) //get current working directory
{
System::String^ strPath = gcnew System::String(buf);
strPath = strPath->Replace("\\","\\\\");
//pathStrLen = strPath->Length;
//size_t sizeinBytes = (pathStrLen + 1)*2;
//copy path string to buf again à¹×èͧ¨Ò¡ÇèÒ buf à´ÔÁ path '\\' Áѹà»ç¹á¤èÍѹà´ÕÂǨеéͧà¾ÔèÁÍÕ¡à·èÒã¹ .net
//new buf ¡ç¨Ðà»ç¹ string ·ÕèÁÕ "\\\\" ã¹ path
pstr = (char*)Runtime::InteropServices::Marshal::StringToHGlobalAnsi(strPath).ToPointer();
strcpy(m_strIniFileName,pstr);
Runtime::InteropServices::Marshal::FreeHGlobal((IntPtr)pstr);
//StringToCharPointer(string, buf,sizeinBytes);
//strcpy(m_strIniFileName,buf);
//copy path of current directory to m_strIniFileName
strcat((char*) m_strIniFileName,g_INI_FName);
manipulateCPFeedINIFile(m_strIniFileName);
}
}
workerThread::~workerThread()
{
WaitForSingleObject(m_hWorker, INFINITE);
CloseHandle(m_hWorker);
}
//manipulate ini File
//------------------------------------------------------
//Name manipulateAPMINIFile
//Desc get dat from INI file
// char* pFileName name and path of ini file
// feed data
//------------------------------------------------------
void workerThread::manipulateCPFeedINIFile(char* pFileName)
{
char* retBuffer;
string strSection ("Parameter");
//¤ÇõÃǨÊͺ¡è͹ÇèÒ ÁÕä¿Åì¹ÕéÍÂÙèËÃ×Íà»ÅèÒ
//set feed type to list
fstream file;
file.open( pFileName, ios::in );
if(file.fail())
{
file.close();
MessageBox::Show("File " + gcnew System::String(pFileName) + " is not exist!!!");
return ;
}
else
{
file.close();
retBuffer = (char*)calloc(MAXSIZE,sizeof(char));
char* pdest = NULL;
char* psrc = NULL;
//read Parameter section data
m_iCapEveryNSec=::GetPrivateProfileIntA(strSection.c_str(),"CapEveryNSec",180,pFileName);
if(m_iCapEveryNSec == 0)
return;
m_iThresDiff=::GetPrivateProfileIntA(strSection.c_str(),"ThresDiff",50,pFileName);
if(m_iThresDiff == 0)
return;
m_iThresShutdownComputer=::GetPrivateProfileIntA(strSection.c_str(),"ThresShutdownComputer",50,pFileName);
if(m_iThresShutdownComputer == 0)
return;
m_iThresBootComputer=::GetPrivateProfileIntA(strSection.c_str(),"ThresBootComputer",50,pFileName);
if(m_iThresBootComputer == 0)
return;
m_iNumberOfDelay=::GetPrivateProfileIntA(strSection.c_str(),"NumberOfDelay",50,pFileName);
if(m_iNumberOfDelay == 0)
return;
}
}
//------------------------------------------------------
//Name updateParamFromINIFile
//Desc parameter modified need to read up-to-date parameter
// unsigned char* pchkModifyParam --check for parameter change 11111 = 63
//------------------------------------------------------
void workerThread::updateParamFromINIFile(unsigned char* pchkModifyParam)
{
unsigned char idxBit;
string strSection ("Parameter");
idxBit = 1 & *pchkModifyParam;
if(idxBit ==1)
{
m_iCapEveryNSec=::GetPrivateProfileIntA(strSection.c_str(),"CapEveryNSec",180,m_strIniFileName);
if(m_iCapEveryNSec == 0)
return;
}
idxBit = 2 & *pchkModifyParam;
if(idxBit ==2)
{
m_iThresDiff=::GetPrivateProfileIntA(strSection.c_str(),"ThresDiff",50,m_strIniFileName);
if(m_iThresDiff == 0)
return;
}
idxBit = 4 & *pchkModifyParam;
if(idxBit ==4)
{
m_iThresShutdownComputer=::GetPrivateProfileIntA(strSection.c_str(),"ThresShutdownComputer",50,m_strIniFileName);
if(m_iThresShutdownComputer == 0)
return;
}
idxBit = 8 & *pchkModifyParam;
if(idxBit ==8)
{
m_iThresBootComputer=::GetPrivateProfileIntA(strSection.c_str(),"ThresBootComputer",50,m_strIniFileName);
if(m_iThresBootComputer == 0)
return;
}
idxBit = 16 & *pchkModifyParam;
if(idxBit ==16)
{
m_iNumberOfDelay=::GetPrivateProfileIntA(strSection.c_str(),"NumberOfDelay",50,m_strIniFileName);
if(m_iNumberOfDelay == 0)
return;
}
//read Parameter section data
}
void workerThread::RequestStop()
{
m_shouldStop = true;
}
//-----------------------------------------------------------
//Name:
//Desc: run motion detection thread
//Usage:
//-----------------------------------------------------------
void workerThread::runMotionDetThread()
{
m_hWorker = (HANDLE)_beginthreadex(NULL,0,ThreadFunc,(void*) this,0,&m_nThreadID); // Thread address
}
cv::Scalar workerThread::iDiffImage(const cv::Mat &image1, const cv::Mat &image2)
{
cv::Mat grayImage1,grayImage2,grayImageTmp;
grayImage1 = cvmConvertToGray(image1);
grayImage2 = cvmConvertToGray(image2);
cv::absdiff(grayImage1, grayImage2, grayImageTmp);
return cv::sum(grayImageTmp);
}
cv::Mat workerThread::cvmConvertToGray(const cv::Mat &inputImage)
{
cv::Mat tmpImage;
if(inputImage.channels() == 3)
{
cv::cvtColor(inputImage, tmpImage, CV_BGR2GRAY);
}
else if(inputImage.channels() == 4)
{
cv::cvtColor(inputImage, tmpImage, CV_BGRA2GRAY);
}
else
tmpImage = inputImage;
return tmpImage;
}
// Draw text into an image. Defaults to top-left-justified text, but you can give negative x coords for right-justified text,
// and/or negative y coords for bottom-justified text.
// Returns the bounding rect around the drawn text.
Rect workerThread::drawString(Mat img, string text, Point coord, Scalar color, float fontScale, int thickness, int fontFace)
{
fontScale = 0.6f;
thickness = 1;
fontFace = FONT_HERSHEY_COMPLEX;
// Get the text size & baseline.
int baseline=0;
Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline);
baseline += thickness;
// Adjust the coords for left/right-justified or top/bottom-justified.
if (coord.y >= 0) {
// Coordinates are for the top-left corner of the text from the top-left of the image, so move down by one row.
coord.y += textSize.height;
}
else {
// Coordinates are for the bottom-left corner of the text from the bottom-left of the image, so come up from the bottom.
coord.y += img.rows - baseline + 1;
}
// Become right-justified if desired.
if (coord.x < 0) {
coord.x += img.cols - textSize.width + 1;
}
// Get the bounding box around the text.
Rect boundingRect = Rect(coord.x, coord.y - textSize.height, textSize.width, baseline + textSize.height);
// Draw anti-aliased text.
putText(img, text, coord, fontFace, fontScale, color, thickness, CV_AA);
// Let the user know how big their text is, in case they want to arrange things.
return boundingRect;
}
cv::Mat workerThread::mCreateDiffMask(const cv::Mat &image1, const cv::Mat &image2, const int &iThreshold, int &iCountPixel)
{
cv::Mat grayImage1,grayImage2,grayImageTmp;
iCountPixel = 0;
grayImage1 = cvmConvertToGray(image1);
grayImage2 = cvmConvertToGray(image2);
cv::absdiff(grayImage1, grayImage2, grayImageTmp);
for(int r=0;r<grayImageTmp.rows;r++)
for(int c=0;c<grayImageTmp.cols;c++)
if(grayImageTmp.at<uchar>(r,c) < iThreshold)
grayImageTmp.at<uchar>(r,c) = 0;
else
iCountPixel++;
return grayImageTmp;
}
string workerThread::mstrPrintNowTime()
{
time_t nowTime;
struct tm *nowStruct;
char strTimeBuf[22] = "";
time(&nowTime);
nowStruct = localtime(&nowTime);
nowStruct->tm_year += 543;
strftime(strTimeBuf,22,"[%d/%m/%Y %H:%M:%S]",nowStruct);
return strTimeBuf;
}
//--------------------------------------------------------------
//Name: Motion Detection
// This method will be called when the thread is started.
// motion detection
//--------------------------------------------------------------
unsigned workerThread::ThreadFunc (LPVOID thisContext)
{
workerThread* pThis = reinterpret_cast<workerThread*>(thisContext);
assert(pThis);
//int iThreshold = (int) thresh;
const int cameraNumber = CV_CAP_ANY;
const int iFPS = 1;
const bool outputDOS = false;
//int m_iCapEveryNSec = 180;
//const int m_iThresDiff = 50;
//const int m_iThresShutdownComputer = 300;
//const int m_iThresBootComputer = 1000;
//const int m_iNumberOfDelay = 100;
// I time it that CAPTURE_EVERY_N_FRAME = 10 uses 1.9 second.
// Thus sec*10/1.9 = number of CAPTURE_EVERY_N_FRAME.
bool bComputerOnOff = true; // Computer is on now.
int iCapEveryNFrame = (int)floor(pThis->m_iCapEveryNSec*10/1.9+0.5);
int iCapEveryNFrameSave = iCapEveryNFrame; // Remember the value.
cv::VideoCapture camera;
camera.open(cameraNumber);
if(!camera.isOpened())
{
cerr << "ERROR: Could not access the camera or video!" << std::endl;
exit(1);
}
camera.set(CV_CAP_PROP_FRAME_WIDTH, 640);
camera.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
camera.set(CV_CAP_PROP_FPS,iFPS);
//cv::Mat currentImage, bgImage = cv::imread("person1.bmp");
cv::Mat currentImage, bgImage, diffImage, displayImage;
ostringstream cvtToString;
std::vector<cv::Mat> imageLayers(3);
int iNumberOfMovePixel = 0;
int iFrameNumber = 0;
camera >> currentImage;
bgImage = currentImage.clone();
#ifdef _SHOWIMG_
cv::flip(bgImage,bgImage,1);
#endif
//Flush image if not when you call you will get old picture.
for(int i=0;i<pThis->m_iNumberOfDelay;i++)
camera >> currentImage;
while(!pThis->m_shouldStop)
{
iNumberOfMovePixel = 0;
camera >> currentImage;
#ifdef _SHOWIMG_
cv::flip(currentImage,currentImage,1);
#endif
diffImage = pThis->mCreateDiffMask(bgImage,currentImage,pThis->m_iThresDiff,iNumberOfMovePixel);
imageLayers[0] = diffImage.clone();
imageLayers[1] = diffImage.clone();
imageLayers[2] = diffImage.clone();
cv::merge(imageLayers,displayImage);
cvtToString << "Moved pixels = " << iNumberOfMovePixel;
if(iFrameNumber == iCapEveryNFrame && bComputerOnOff == true &&
iNumberOfMovePixel < pThis->m_iThresShutdownComputer)
{
bComputerOnOff = false;
if(outputDOS)
cout << pThis->mstrPrintNowTime() << " shutdown" << endl;
iCapEveryNFrame = 10;
iFrameNumber = 0;
//turn off monitor
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) 2);
}
else if(bComputerOnOff == false && iNumberOfMovePixel > pThis->m_iThresBootComputer)
{
bComputerOnOff = true;
if(outputDOS)
cout << pThis->mstrPrintNowTime() << " Boot com" << endl;
iCapEveryNFrame = iCapEveryNFrameSave;
iFrameNumber = 0;
//turn on monitor
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) -1);
}else if(iFrameNumber == iCapEveryNFrame && bComputerOnOff == true)
{
iFrameNumber = 0;
/*QueryPerformanceCounter(&nsStop);
if(outputDOS)
{
nsDiff = (double)(nsStop.QuadPart - nsStart.QuadPart)/(double)(nsQuantum.QuadPart);
cout << "Nano sec = " << nsDiff << " seconds" << endl;
}
nsStart = nsStop;*/
}
#ifdef _SHOWIMG_
if(outputDOS)
{
pThis->drawString(displayImage, cvtToString.str(), Point(10, 10), CV_RGB(0,255,0));
cv::namedWindow("mainWindows");
cv::imshow("mainWindows",displayImage);
cv::waitKey(33);
cvtToString.str("");
}
#endif
bgImage = currentImage.clone();
iFrameNumber++;
}
//_endthreadex( 0 ); //_endthreadex, it causes its thread object to go to the signaled state. Êè§ä»Âѧ main thread ·ÕèÃÍ WaitForSingleObject
return 0;
}
/*void workerThread::DoWork(Object^ data)
{
// threshold for motion dectection
int iThreshold = (int)data;
int cameraNumber = CV_CAP_ANY;
int iComputerOnOff = 1;
int iFPS = 1;
cv::VideoCapture camera;
camera.open(cameraNumber);
if(!camera.isOpened())
{
cerr << "ERROR: Could not access the camera or video!" << std::endl;
exit(1);
}
camera.set(CV_CAP_PROP_FRAME_WIDTH, 640);
camera.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
camera.set(CV_CAP_PROP_FPS,iFPS);
//cv::Mat currentImage, bgImage = cv::imread("person1.bmp");
cv::Mat currentImage, bgImage, diffImage, displayImage;
ostringstream cvtToString;
std::vector<cv::Mat> imageLayers(3);
int iMovePixel = 0;
int iFrameAt = 0;
camera >> currentImage;
bgImage = currentImage.clone();
cv::flip(bgImage,bgImage,1);
while(!m_shouldStop)
{
camera >> currentImage;
cv::flip(currentImage,currentImage,1);
iMovePixel = 0;
#ifdef _SHOWIMG_
cv::imshow("c",currentImage);
cv::waitKey(33);
cv::imshow("b",bgImage);
cv::waitKey(33);
#endif
diffImage = mCreateDiffMask(bgImage,currentImage,iThreshold,iMovePixel);
imageLayers[0] = diffImage.clone();
imageLayers[1] = diffImage.clone();
imageLayers[2] = diffImage.clone();
cv::merge(imageLayers,displayImage);
cvtToString << "Moved pixels = " << iMovePixel;
if(iFrameAt == 5 && iComputerOnOff == 1 && iMovePixel < 10)
{
iComputerOnOff = 0;
cout << "shutdown" << endl;
iFrameAt = 0;
}
else if(iComputerOnOff == 0 && iMovePixel > 50)
{
iComputerOnOff = 1;
cout << "Boot com" << endl;
iFrameAt = 0;
}else if(iFrameAt == 5 && iComputerOnOff == 1)
iFrameAt = 0;
drawString(displayImage, cvtToString.str(), Point(10, 10), CV_RGB(0,255,0));
cv::namedWindow("mainWindows");
cv::imshow("mainWindows",displayImage);
cv::waitKey(33);
cvtToString.str("");
bgImage = currentImage.clone();
iFrameAt++;
}
//worker thread: terminating gracefully
}*/
}