3 * Copyright (C) 2011 Robert Jobbagy <jobbagy.robert@gmail.com>
4 * Copyright (C) 2011 Nicola Murino <nicola.murino@gmail.com>
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
24 * Alternatively, the contents of this file may be used under the
25 * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
26 * which case the following provisions apply instead of the ones
29 * This library is free software; you can redistribute it and/or
30 * modify it under the terms of the GNU Library General Public
31 * License as published by the Free Software Foundation; either
32 * version 2 of the License, or (at your option) any later version.
34 * This library is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
37 * Library General Public License for more details.
39 * You should have received a copy of the GNU Library General Public
40 * License along with this library; if not, write to the
41 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
42 * Boston, MA 02111-1307, USA.
49 #include <arpa/inet.h>
50 #include "MotionCells.h"
52 uint64_t ntohl64 (uint64_t val);
53 uint64_t htonl64 (uint64_t val);
56 ntohl64 (uint64_t val)
59 uint32_t low = (uint32_t) (val & 0x00000000FFFFFFFFLL);
60 uint32_t high = (uint32_t) ((val & 0xFFFFFFFF00000000LL) >> 32);
63 res64 = (uint64_t) high + (((uint64_t) low) << 32);
69 htonl64 (uint64_t val)
72 uint32_t low = (uint32_t) (val & 0x00000000FFFFFFFFLL);
73 uint32_t high = (uint32_t) ((val & 0xFFFFFFFF00000000LL) >> 32);
76 res64 = (uint64_t) high + (((uint64_t) low) << 32);
80 MotionCells::MotionCells ()
83 m_motioncells_idx_count = 0;
84 m_motioncellsidxcstr = NULL;
85 m_saveInDatafile = false;
89 transparencyimg = NULL;
90 m_pdifferenceImage = NULL;
92 m_initdatafilefailed = new char[BUSMSGLEN];
93 m_savedatafilefailed = new char[BUSMSGLEN];
101 MotionCells::~MotionCells ()
104 fclose (mc_savefile);
107 delete[]m_initdatafilefailed;
108 delete[]m_savedatafilefailed;
109 if (m_motioncellsidxcstr)
110 delete[]m_motioncellsidxcstr;
112 cvReleaseImage (&m_pcurFrame);
114 cvReleaseImage (&m_pprevFrame);
116 cvReleaseImage (&transparencyimg);
117 if (m_pdifferenceImage)
118 cvReleaseImage (&m_pdifferenceImage);
120 cvReleaseImage (&m_pbwImage);
124 MotionCells::performDetectionMotionCells (IplImage * p_frame,
125 double p_sensitivity, double p_framerate, int p_gridx, int p_gridy,
126 gint64 timestamp_millisec, bool p_isVisible, bool p_useAlpha,
127 int motionmaskcoord_count, motionmaskcoordrect * motionmaskcoords,
128 int motionmaskcells_count, motioncellidx * motionmaskcellsidx,
129 cellscolor motioncellscolor, int motioncells_count,
130 motioncellidx * motioncellsidx, gint64 starttime, char *p_datafile,
131 bool p_changed_datafile, int p_thickness)
136 p_framerate >= 1 ? p_framerate <= 5 ? sumframecnt = 1
137 : p_framerate <= 10 ? sumframecnt = 2
138 : p_framerate <= 15 ? sumframecnt = 3
139 : p_framerate <= 20 ? sumframecnt = 4
140 : p_framerate <= 25 ? sumframecnt = 5 : sumframecnt = 0 : sumframecnt = 0;
143 m_changed_datafile = p_changed_datafile;
144 if (m_framecnt >= sumframecnt) {
145 m_useAlpha = p_useAlpha;
148 if (m_changed_datafile) {
149 ret = initDataFile (p_datafile, starttime);
154 m_frameSize = cvGetSize (p_frame);
155 m_frameSize.width /= 2;
156 m_frameSize.height /= 2;
157 setMotionCells (m_frameSize.width, m_frameSize.height);
158 m_sensitivity = 1 - p_sensitivity;
159 m_isVisible = p_isVisible;
160 m_pcurFrame = cvCloneImage (p_frame);
161 IplImage *m_pcurgreyImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
162 IplImage *m_pprevgreyImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
163 IplImage *m_pgreyImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
164 IplImage *m_pcurDown =
165 cvCreateImage (m_frameSize, m_pcurFrame->depth, m_pcurFrame->nChannels);
166 IplImage *m_pprevDown = cvCreateImage (m_frameSize, m_pprevFrame->depth,
167 m_pprevFrame->nChannels);
168 m_pbwImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
169 cvPyrDown (m_pprevFrame, m_pprevDown);
170 cvCvtColor (m_pprevDown, m_pprevgreyImage, CV_RGB2GRAY);
172 cvReleaseImage (&m_pprevFrame);
173 cvPyrDown (m_pcurFrame, m_pcurDown);
174 cvCvtColor (m_pcurDown, m_pcurgreyImage, CV_RGB2GRAY);
175 m_pdifferenceImage = cvCloneImage (m_pcurgreyImage);
176 //cvSmooth(m_pcurgreyImage, m_pcurgreyImage, CV_GAUSSIAN, 3, 0);//TODO camera noise reduce,something smoothing, and rethink runningavg weights
178 //Minus the current gray frame from the 8U moving average.
179 cvAbsDiff (m_pprevgreyImage, m_pcurgreyImage, m_pdifferenceImage);
181 //Convert the image to black and white.
182 cvAdaptiveThreshold (m_pdifferenceImage, m_pbwImage, 255,
183 CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV, 7);
185 // Dilate and erode to get object blobs
186 cvDilate (m_pbwImage, m_pbwImage, NULL, 2);
187 cvErode (m_pbwImage, m_pbwImage, NULL, 2);
189 //mask-out the overlay on difference image
190 if (motionmaskcoord_count > 0)
191 performMotionMaskCoords (motionmaskcoords, motionmaskcoord_count);
192 if (motionmaskcells_count > 0)
193 performMotionMask (motionmaskcellsidx, motionmaskcells_count);
194 if (getIsNonZero (m_pbwImage)) { //detect Motion
195 GST_DEBUG ("DETECT MOTION \n");
196 if (m_MotionCells.size () > 0) //it contains previous motioncells what we used when frames dropped
197 m_MotionCells.clear ();
199 cvReleaseImage (&transparencyimg);
200 (motioncells_count > 0) ?
201 calculateMotionPercentInMotionCells (motioncellsidx,
203 : calculateMotionPercentInMotionCells (motionmaskcellsidx, 0);
205 transparencyimg = cvCreateImage (cvGetSize (p_frame), p_frame->depth, 3);
206 cvSetZero (transparencyimg);
207 if (m_motioncellsidxcstr)
208 delete[]m_motioncellsidxcstr;
209 m_motioncells_idx_count = m_MotionCells.size () * MSGLEN; //one motion cell idx: (lin idx : col idx,) it's 4 character except last motion cell idx
210 m_motioncellsidxcstr = new char[m_motioncells_idx_count];
211 char *tmpstr = new char[MSGLEN];
212 for (int i = 0; i < MSGLEN; i++)
214 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
216 pt1.x = m_MotionCells.at (i).cell_pt1.x * 2;
217 pt1.y = m_MotionCells.at (i).cell_pt1.y * 2;
218 pt2.x = m_MotionCells.at (i).cell_pt2.x * 2;
219 pt2.y = m_MotionCells.at (i).cell_pt2.y * 2;
220 if (m_useAlpha && m_isVisible) {
221 cvRectangle (transparencyimg,
224 CV_RGB (motioncellscolor.B_channel_value,
225 motioncellscolor.G_channel_value,
226 motioncellscolor.R_channel_value), CV_FILLED);
227 } else if (m_isVisible) {
228 cvRectangle (p_frame,
231 CV_RGB (motioncellscolor.B_channel_value,
232 motioncellscolor.G_channel_value,
233 motioncellscolor.R_channel_value), p_thickness);
236 if (i < m_MotionCells.size () - 1) {
237 snprintf (tmpstr, MSGLEN, "%d:%d,", m_MotionCells.at (i).lineidx,
238 m_MotionCells.at (i).colidx);
240 snprintf (tmpstr, MSGLEN, "%d:%d", m_MotionCells.at (i).lineidx,
241 m_MotionCells.at (i).colidx);
244 strncpy (m_motioncellsidxcstr, tmpstr, m_motioncells_idx_count);
246 strcat (m_motioncellsidxcstr, tmpstr);
248 if (m_MotionCells.size () == 0)
249 strncpy (m_motioncellsidxcstr, " ", m_motioncells_idx_count);
251 if (m_useAlpha && m_isVisible) {
252 if (m_MotionCells.size () > 0)
253 blendImages (p_frame, transparencyimg, m_alpha, m_beta);
258 if (mc_savefile && m_saveInDatafile) {
259 ret = saveMotionCells (timestamp_millisec);
264 m_motioncells_idx_count = 0;
265 if (m_MotionCells.size () > 0)
266 m_MotionCells.clear ();
268 cvReleaseImage (&transparencyimg);
271 m_pprevFrame = cvCloneImage (m_pcurFrame);
274 cvReleaseImage (&m_pcurFrame);
275 if (m_pdifferenceImage)
276 cvReleaseImage (&m_pdifferenceImage);
278 cvReleaseImage (&m_pcurgreyImage);
279 if (m_pprevgreyImage)
280 cvReleaseImage (&m_pprevgreyImage);
282 cvReleaseImage (&m_pgreyImage);
284 cvReleaseImage (&m_pbwImage);
286 cvReleaseImage (&m_pprevDown);
288 cvReleaseImage (&m_pcurDown);
290 for (int i = 0; i < m_gridy; ++i) {
296 if (p_framerate <= 5) {
297 if (m_MotionCells.size () > 0)
298 m_MotionCells.clear ();
300 cvReleaseImage (&transparencyimg);
302 } else { //we do frame drop
303 m_motioncells_idx_count = 0;
305 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
307 pt1.x = m_MotionCells.at (i).cell_pt1.x * 2;
308 pt1.y = m_MotionCells.at (i).cell_pt1.y * 2;
309 pt2.x = m_MotionCells.at (i).cell_pt2.x * 2;
310 pt2.y = m_MotionCells.at (i).cell_pt2.y * 2;
311 if (m_useAlpha && m_isVisible) {
312 cvRectangle (transparencyimg,
315 CV_RGB (motioncellscolor.B_channel_value,
316 motioncellscolor.G_channel_value,
317 motioncellscolor.R_channel_value), CV_FILLED);
318 } else if (m_isVisible) {
319 cvRectangle (p_frame,
322 CV_RGB (motioncellscolor.B_channel_value,
323 motioncellscolor.G_channel_value,
324 motioncellscolor.R_channel_value), p_thickness);
328 if (m_useAlpha && m_isVisible) {
329 if (m_MotionCells.size () > 0)
330 blendImages (p_frame, transparencyimg, m_alpha, m_beta);
337 MotionCells::initDataFile (char *p_datafile, gint64 starttime) //p_date is increased with difference between current and previous buffer ts
340 if (strncmp (p_datafile, " ", 1)) {
341 mc_savefile = fopen (p_datafile, "w");
342 if (mc_savefile == NULL) {
343 //fprintf(stderr, "%s %d:initDataFile:fopen:%d (%s)\n", __FILE__, __LINE__, errno,
345 strncpy (m_initdatafilefailed, strerror (errno), BUSMSGLEN - 1);
346 m_initerrorcode = errno;
349 m_saveInDatafile = true;
353 bzero (&m_header, sizeof (MotionCellHeader));
354 m_header.headersize = htonl (MC_HEADER);
355 m_header.type = htonl (MC_TYPE);
356 m_header.version = htonl (MC_VERSION);
357 //it needs these bytes
359 htonl ((int) ceil (ceil (m_gridx * m_gridy / 8.0) / 4.0) * 4 +
360 sizeof (mcd.timestamp));
361 m_header.gridx = htonl (m_gridx);
362 m_header.gridy = htonl (m_gridy);
363 m_header.starttime = htonl64 (starttime);
365 snprintf (m_header.name, sizeof (m_header.name), "%s %dx%d", MC_VERSIONTEXT,
366 ntohl (m_header.gridx), ntohl (m_header.gridy));
367 m_changed_datafile = false;
372 MotionCells::saveMotionCells (gint64 timestamp_millisec)
375 MotionCellData mc_data;
376 mc_data.timestamp = htonl (timestamp_millisec);
378 //There is no datafile
379 if (mc_savefile == NULL)
382 if (ftello (mc_savefile) == 0) {
383 //cerr << "Writing out file header"<< m_header.headersize <<":" << sizeof(MotionCellHeader) << " itemsize:"
384 //<< m_header.itemsize << endl;
385 if (fwrite (&m_header, sizeof (MotionCellHeader), 1, mc_savefile) != 1) {
386 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
388 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
389 m_saveerrorcode = errno;
396 ntohl (m_header.itemsize) - sizeof (mc_data.timestamp));
397 if (mc_data.data == NULL) {
398 //fprintf(stderr, "%s %d:saveMotionCells:calloc:%d (%s)\n", __FILE__, __LINE__, errno,
400 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
401 m_saveerrorcode = errno;
405 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
407 m_MotionCells.at (i).lineidx * ntohl (m_header.gridx) +
408 m_MotionCells.at (i).colidx;
409 int bytenum = (int) floor (bitnum / 8.0);
410 int shift = bitnum - bytenum * 8;
411 mc_data.data[bytenum] = mc_data.data[bytenum] | (1 << shift);
412 //cerr << "Motion Detected " << "line:" << m_MotionCells.at(i).lineidx << " col:" << m_MotionCells.at(i).colidx;
413 //cerr << " bitnum " << bitnum << " bytenum " << bytenum << " shift " << shift << " value " << (int)mc_data.data[bytenum] << endl;
416 if (fwrite (&mc_data.timestamp, sizeof (mc_data.timestamp), 1,
418 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
420 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
421 m_saveerrorcode = errno;
425 if (fwrite (mc_data.data,
426 ntohl (m_header.itemsize) - sizeof (mc_data.timestamp), 1,
428 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
430 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
431 m_saveerrorcode = errno;
440 MotionCells::calculateMotionPercentInCell (int p_row, int p_col,
441 double *p_cellarea, double *p_motionarea)
443 double cntpixelsnum = 0;
444 double cntmotionpixelnum = 0;
446 int ybegin = floor ((double) p_row * m_cellheight);
447 int yend = floor ((double) (p_row + 1) * m_cellheight);
448 int xbegin = floor ((double) (p_col) * m_cellwidth);
449 int xend = floor ((double) (p_col + 1) * m_cellwidth);
450 int cellw = xend - xbegin;
451 int cellh = yend - ybegin;
452 int cellarea = cellw * cellh;
453 *p_cellarea = cellarea;
454 int thresholdmotionpixelnum = floor ((double) cellarea * m_sensitivity);
456 for (int i = ybegin; i < yend; i++) {
457 for (int j = xbegin; j < xend; j++) {
459 if ((((uchar *) (m_pbwImage->imageData + m_pbwImage->widthStep * i))[j]) >
462 if (cntmotionpixelnum >= thresholdmotionpixelnum) { //we dont needs calculate anymore
463 *p_motionarea = cntmotionpixelnum;
464 return (cntmotionpixelnum / cntpixelsnum);
467 int remainingpixelsnum = cellarea - cntpixelsnum;
468 if ((cntmotionpixelnum + remainingpixelsnum) < thresholdmotionpixelnum) { //moving pixels number will be less than threshold
475 return (cntmotionpixelnum / cntpixelsnum);
479 MotionCells::calculateMotionPercentInMotionCells (motioncellidx *
480 p_motioncellsidx, int p_motioncells_count)
482 if (p_motioncells_count == 0) {
483 for (int i = 0; i < m_gridy; i++) {
484 for (int j = 0; j < m_gridx; j++) {
485 m_pCells[i][j].MotionPercent = calculateMotionPercentInCell (i, j,
486 &m_pCells[i][j].CellArea, &m_pCells[i][j].MotionArea);
487 m_pCells[i][j].hasMotion =
488 m_sensitivity < m_pCells[i][j].MotionPercent ? true : false;
489 if (m_pCells[i][j].hasMotion) {
493 mci.cell_pt1.x = floor ((double) j * m_cellwidth);
494 mci.cell_pt1.y = floor ((double) i * m_cellheight);
495 mci.cell_pt2.x = floor ((double) (j + 1) * m_cellwidth);
496 mci.cell_pt2.y = floor ((double) (i + 1) * m_cellheight);
497 int w = mci.cell_pt2.x - mci.cell_pt1.x;
498 int h = mci.cell_pt2.y - mci.cell_pt1.y;
499 mci.motioncell = cvRect (mci.cell_pt1.x, mci.cell_pt1.y, w, h);
500 m_MotionCells.push_back (mci);
505 for (int k = 0; k < p_motioncells_count; ++k) {
507 int i = p_motioncellsidx[k].lineidx;
508 int j = p_motioncellsidx[k].columnidx;
509 m_pCells[i][j].MotionPercent =
510 calculateMotionPercentInCell (i, j,
511 &m_pCells[i][j].CellArea, &m_pCells[i][j].MotionArea);
512 m_pCells[i][j].hasMotion =
513 m_pCells[i][j].MotionPercent > m_sensitivity ? true : false;
514 if (m_pCells[i][j].hasMotion) {
516 mci.lineidx = p_motioncellsidx[k].lineidx;
517 mci.colidx = p_motioncellsidx[k].columnidx;
518 mci.cell_pt1.x = floor ((double) j * m_cellwidth);
519 mci.cell_pt1.y = floor ((double) i * m_cellheight);
520 mci.cell_pt2.x = floor ((double) (j + 1) * m_cellwidth);
521 mci.cell_pt2.y = floor ((double) (i + 1) * m_cellheight);
522 int w = mci.cell_pt2.x - mci.cell_pt1.x;
523 int h = mci.cell_pt2.y - mci.cell_pt1.y;
524 mci.motioncell = cvRect (mci.cell_pt1.x, mci.cell_pt1.y, w, h);
525 m_MotionCells.push_back (mci);
532 MotionCells::performMotionMaskCoords (motionmaskcoordrect * p_motionmaskcoords,
533 int p_motionmaskcoords_count)
541 for (int i = 0; i < p_motionmaskcoords_count; i++) {
542 upperleft.x = p_motionmaskcoords[i].upper_left_x;
543 upperleft.y = p_motionmaskcoords[i].upper_left_y;
544 lowerright.x = p_motionmaskcoords[i].lower_right_x;
545 lowerright.y = p_motionmaskcoords[i].lower_right_y;
546 cvRectangle (m_pbwImage, upperleft, lowerright, CV_RGB (0, 0, 0),
552 MotionCells::performMotionMask (motioncellidx * p_motionmaskcellsidx,
553 int p_motionmaskcells_count)
555 for (int k = 0; k < p_motionmaskcells_count; k++) {
556 int beginy = p_motionmaskcellsidx[k].lineidx * m_cellheight;
557 int beginx = p_motionmaskcellsidx[k].columnidx * m_cellwidth;
559 (double) p_motionmaskcellsidx[k].columnidx * m_cellwidth + m_cellwidth;
561 (double) p_motionmaskcellsidx[k].lineidx * m_cellheight + m_cellheight;
562 for (int i = beginy; i < endy; i++)
563 for (int j = beginx; j < endx; j++) {
564 ((uchar *) (m_pbwImage->imageData + m_pbwImage->widthStep * i))[j] = 0;
569 ///BGR if we use only OpenCV
570 //RGB if we use gst+OpenCV
572 MotionCells::blendImages (IplImage * p_actFrame, IplImage * p_cellsFrame,
573 float p_alpha, float p_beta)
576 int height = p_actFrame->height;
577 int width = p_actFrame->width;
578 int step = p_actFrame->widthStep / sizeof (uchar);
579 int channels = p_actFrame->nChannels;
580 int cellstep = p_cellsFrame->widthStep / sizeof (uchar);
581 uchar *curImageData = (uchar *) p_actFrame->imageData;
582 uchar *cellImageData = (uchar *) p_cellsFrame->imageData;
584 for (int i = 0; i < height; i++)
585 for (int j = 0; j < width; j++)
586 for (int k = 0; k < channels; k++)
587 if (cellImageData[i * cellstep + j * channels + k] > 0) {
588 curImageData[i * step + j * channels + k] =
589 round ((double) curImageData[i * step + j * channels +
590 k] * p_alpha + ((double) cellImageData[i * cellstep +
591 j * channels + k] * p_beta));