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., 51 Franklin St, Fifth Floor,
42 * Boston, MA 02110-1301, USA.
50 #include "MotionCells.h"
51 #include <opencv2/imgproc.hpp>
53 MotionCells::MotionCells ()
56 m_motioncells_idx_count = 0;
57 m_motioncellsidxcstr = NULL;
58 m_saveInDatafile = false;
62 transparencyimg = NULL;
63 m_pdifferenceImage = NULL;
65 m_initdatafilefailed = new char[BUSMSGLEN];
66 m_savedatafilefailed = new char[BUSMSGLEN];
79 m_changed_datafile = false;
81 memset (&m_header, 0, sizeof (MotionCellHeader));
82 m_header.headersize = GINT32_TO_BE (MC_HEADER);
83 m_header.type = GINT32_TO_BE (MC_TYPE);
84 m_header.version = GINT32_TO_BE (MC_VERSION);
85 m_header.itemsize = 0;
88 m_header.starttime = 0;
91 MotionCells::~MotionCells ()
97 delete[]m_initdatafilefailed;
98 delete[]m_savedatafilefailed;
99 if (m_motioncellsidxcstr)
100 delete[]m_motioncellsidxcstr;
102 cvReleaseImage (&m_pcurFrame);
104 cvReleaseImage (&m_pprevFrame);
106 cvReleaseImage (&transparencyimg);
107 if (m_pdifferenceImage)
108 cvReleaseImage (&m_pdifferenceImage);
110 cvReleaseImage (&m_pbwImage);
114 MotionCells::performDetectionMotionCells (IplImage * p_frame,
115 double p_sensitivity, double p_framerate, int p_gridx, int p_gridy,
116 gint64 timestamp_millisec, bool p_isVisible, bool p_useAlpha,
117 int motionmaskcoord_count, motionmaskcoordrect * motionmaskcoords,
118 int motionmaskcells_count, motioncellidx * motionmaskcellsidx,
119 cellscolor motioncellscolor, int motioncells_count,
120 motioncellidx * motioncellsidx, gint64 starttime, char *p_datafile,
121 bool p_changed_datafile, int p_thickness)
128 p_framerate >= 1 ? p_framerate <= 5 ? sumframecnt = 1
129 : p_framerate <= 10 ? sumframecnt = 2
130 : p_framerate <= 15 ? sumframecnt = 3
131 : p_framerate <= 20 ? sumframecnt = 4
132 : p_framerate <= 25 ? sumframecnt = 5
133 : p_framerate <= 30 ? sumframecnt = 6 : sumframecnt = 0 : sumframecnt = 0;
136 m_changed_datafile = p_changed_datafile;
137 if (m_framecnt >= sumframecnt) {
138 m_useAlpha = p_useAlpha;
141 if (m_changed_datafile) {
142 ret = initDataFile (p_datafile, starttime);
147 frameSize = cvGetSize (p_frame);
148 frameSize.width /= 2;
149 frameSize.height /= 2;
150 setMotionCells (frameSize.width, frameSize.height);
151 m_sensitivity = 1 - p_sensitivity;
152 m_isVisible = p_isVisible;
153 m_pcurFrame = cvCloneImage (p_frame);
154 IplImage *m_pcurgreyImage = cvCreateImage (frameSize, IPL_DEPTH_8U, 1);
155 IplImage *m_pprevgreyImage = cvCreateImage (frameSize, IPL_DEPTH_8U, 1);
156 IplImage *m_pgreyImage = cvCreateImage (frameSize, IPL_DEPTH_8U, 1);
157 IplImage *m_pcurDown =
158 cvCreateImage (frameSize, m_pcurFrame->depth, m_pcurFrame->nChannels);
159 IplImage *m_pprevDown = cvCreateImage (frameSize, m_pprevFrame->depth,
160 m_pprevFrame->nChannels);
161 m_pbwImage = cvCreateImage (frameSize, IPL_DEPTH_8U, 1);
162 cvPyrDown (m_pprevFrame, m_pprevDown);
163 cvCvtColor (m_pprevDown, m_pprevgreyImage, CV_RGB2GRAY);
164 cvPyrDown (m_pcurFrame, m_pcurDown);
165 cvCvtColor (m_pcurDown, m_pcurgreyImage, CV_RGB2GRAY);
166 m_pdifferenceImage = cvCloneImage (m_pcurgreyImage);
167 //cvSmooth(m_pcurgreyImage, m_pcurgreyImage, CV_GAUSSIAN, 3, 0);//TODO camera noise reduce,something smoothing, and rethink runningavg weights
169 //Minus the current gray frame from the 8U moving average.
170 cvAbsDiff (m_pprevgreyImage, m_pcurgreyImage, m_pdifferenceImage);
172 //Convert the image to black and white.
173 cvAdaptiveThreshold (m_pdifferenceImage, m_pbwImage, 255,
174 CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV, 7);
176 // Dilate and erode to get object blobs
177 cvDilate (m_pbwImage, m_pbwImage, NULL, 2);
178 cvErode (m_pbwImage, m_pbwImage, NULL, 2);
180 //mask-out the overlay on difference image
181 if (motionmaskcoord_count > 0)
182 performMotionMaskCoords (motionmaskcoords, motionmaskcoord_count);
183 if (motionmaskcells_count > 0)
184 performMotionMask (motionmaskcellsidx, motionmaskcells_count);
185 if (getIsNonZero (m_pbwImage)) { //detect Motion
186 if (m_MotionCells.size () > 0) //it contains previous motioncells what we used when frames dropped
187 m_MotionCells.clear ();
189 cvReleaseImage (&transparencyimg);
190 (motioncells_count > 0) ?
191 calculateMotionPercentInMotionCells (motioncellsidx,
193 : calculateMotionPercentInMotionCells (motionmaskcellsidx, 0);
195 transparencyimg = cvCreateImage (cvGetSize (p_frame), p_frame->depth, 3);
196 cvSetZero (transparencyimg);
197 if (m_motioncellsidxcstr)
198 delete[]m_motioncellsidxcstr;
199 m_motioncells_idx_count = m_MotionCells.size () * MSGLEN; //one motion cell idx: (lin idx : col idx,) it's up to 6 character except last motion cell idx
200 m_motioncellsidxcstr = new char[m_motioncells_idx_count];
201 char *tmpstr = new char[MSGLEN + 1];
203 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
205 pt1.x = m_MotionCells.at (i).cell_pt1.x * 2;
206 pt1.y = m_MotionCells.at (i).cell_pt1.y * 2;
207 pt2.x = m_MotionCells.at (i).cell_pt2.x * 2;
208 pt2.y = m_MotionCells.at (i).cell_pt2.y * 2;
209 if (m_useAlpha && m_isVisible) {
210 cvRectangle (transparencyimg,
213 CV_RGB (motioncellscolor.B_channel_value,
214 motioncellscolor.G_channel_value,
215 motioncellscolor.R_channel_value), CV_FILLED);
216 } else if (m_isVisible) {
217 cvRectangle (p_frame,
220 CV_RGB (motioncellscolor.B_channel_value,
221 motioncellscolor.G_channel_value,
222 motioncellscolor.R_channel_value), p_thickness);
225 if (i < m_MotionCells.size () - 1) {
226 snprintf (tmpstr, MSGLEN + 1, "%d:%d,", m_MotionCells.at (i).lineidx,
227 m_MotionCells.at (i).colidx);
229 snprintf (tmpstr, MSGLEN + 1, "%d:%d", m_MotionCells.at (i).lineidx,
230 m_MotionCells.at (i).colidx);
233 strncpy (m_motioncellsidxcstr, tmpstr, m_motioncells_idx_count);
235 strcat (m_motioncellsidxcstr, tmpstr);
237 if (m_MotionCells.size () == 0)
238 strncpy (m_motioncellsidxcstr, " ", m_motioncells_idx_count);
240 if (m_useAlpha && m_isVisible) {
241 if (m_MotionCells.size () > 0)
242 blendImages (p_frame, transparencyimg, m_alpha, m_beta);
247 if (mc_savefile && m_saveInDatafile) {
248 ret = saveMotionCells (timestamp_millisec);
253 m_motioncells_idx_count = 0;
254 if (m_MotionCells.size () > 0)
255 m_MotionCells.clear ();
257 cvReleaseImage (&transparencyimg);
261 cvReleaseImage (&m_pprevFrame);
262 m_pprevFrame = cvCloneImage (m_pcurFrame);
265 cvReleaseImage (&m_pcurFrame);
266 if (m_pdifferenceImage)
267 cvReleaseImage (&m_pdifferenceImage);
269 cvReleaseImage (&m_pcurgreyImage);
270 if (m_pprevgreyImage)
271 cvReleaseImage (&m_pprevgreyImage);
273 cvReleaseImage (&m_pgreyImage);
275 cvReleaseImage (&m_pbwImage);
277 cvReleaseImage (&m_pprevDown);
279 cvReleaseImage (&m_pcurDown);
281 for (int i = 0; i < m_gridy; ++i) {
287 if (p_framerate <= 5) {
288 if (m_MotionCells.size () > 0)
289 m_MotionCells.clear ();
291 cvReleaseImage (&transparencyimg);
293 } else { //we do frame drop
294 m_motioncells_idx_count = 0;
296 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
298 pt1.x = m_MotionCells.at (i).cell_pt1.x * 2;
299 pt1.y = m_MotionCells.at (i).cell_pt1.y * 2;
300 pt2.x = m_MotionCells.at (i).cell_pt2.x * 2;
301 pt2.y = m_MotionCells.at (i).cell_pt2.y * 2;
302 if (m_useAlpha && m_isVisible) {
303 cvRectangle (transparencyimg,
306 CV_RGB (motioncellscolor.B_channel_value,
307 motioncellscolor.G_channel_value,
308 motioncellscolor.R_channel_value), CV_FILLED);
309 } else if (m_isVisible) {
310 cvRectangle (p_frame,
313 CV_RGB (motioncellscolor.B_channel_value,
314 motioncellscolor.G_channel_value,
315 motioncellscolor.R_channel_value), p_thickness);
319 if (m_useAlpha && m_isVisible) {
320 if (m_MotionCells.size () > 0)
321 blendImages (p_frame, transparencyimg, m_alpha, m_beta);
328 MotionCells::initDataFile (char *p_datafile, gint64 starttime) //p_date is increased with difference between current and previous buffer ts
331 if (strncmp (p_datafile, " ", 1)) {
332 mc_savefile = fopen (p_datafile, "w");
333 if (mc_savefile == NULL) {
334 //fprintf(stderr, "%s %d:initDataFile:fopen:%d (%s)\n", __FILE__, __LINE__, errno,
336 strncpy (m_initdatafilefailed, strerror (errno), BUSMSGLEN - 1);
337 m_initerrorcode = errno;
340 m_saveInDatafile = true;
345 //it needs these bytes
347 GINT32_TO_BE ((int) ceil (ceil (m_gridx * m_gridy / 8.0) / 4.0) * 4 +
348 sizeof (mcd.timestamp));
349 m_header.gridx = GINT32_TO_BE (m_gridx);
350 m_header.gridy = GINT32_TO_BE (m_gridy);
351 m_header.starttime = GINT64_TO_BE (starttime);
353 snprintf (m_header.name, sizeof (m_header.name), "%s %dx%d", MC_VERSIONTEXT,
354 GINT32_FROM_BE (m_header.gridx), GINT32_FROM_BE (m_header.gridy));
355 m_changed_datafile = false;
360 MotionCells::saveMotionCells (gint64 timestamp_millisec)
363 MotionCellData mc_data;
364 mc_data.timestamp = GINT32_TO_BE (timestamp_millisec);
366 //There is no datafile
367 if (mc_savefile == NULL)
370 if (ftello (mc_savefile) == 0) {
371 //cerr << "Writing out file header"<< m_header.headersize <<":" << sizeof(MotionCellHeader) << " itemsize:"
372 //<< m_header.itemsize << endl;
373 if (fwrite (&m_header, sizeof (MotionCellHeader), 1, mc_savefile) != 1) {
374 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
376 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
377 m_saveerrorcode = errno;
384 GINT32_FROM_BE (m_header.itemsize) - sizeof (mc_data.timestamp));
385 if (mc_data.data == NULL) {
386 //fprintf(stderr, "%s %d:saveMotionCells:calloc:%d (%s)\n", __FILE__, __LINE__, errno,
388 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
389 m_saveerrorcode = errno;
393 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
395 m_MotionCells.at (i).lineidx * GINT32_FROM_BE (m_header.gridx) +
396 m_MotionCells.at (i).colidx;
397 int bytenum = (int) floor (bitnum / 8.0);
398 int shift = bitnum - bytenum * 8;
399 mc_data.data[bytenum] = mc_data.data[bytenum] | (1 << shift);
400 //cerr << "Motion Detected " << "line:" << m_MotionCells.at(i).lineidx << " col:" << m_MotionCells.at(i).colidx;
401 //cerr << " bitnum " << bitnum << " bytenum " << bytenum << " shift " << shift << " value " << (int)mc_data.data[bytenum] << endl;
404 if (fwrite (&mc_data.timestamp, sizeof (mc_data.timestamp), 1,
406 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
408 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
409 m_saveerrorcode = errno;
413 if (fwrite (mc_data.data,
414 GINT32_FROM_BE (m_header.itemsize) - sizeof (mc_data.timestamp), 1,
416 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
418 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
419 m_saveerrorcode = errno;
428 MotionCells::calculateMotionPercentInCell (int p_row, int p_col,
429 double *p_cellarea, double *p_motionarea)
431 double cntpixelsnum = 0;
432 double cntmotionpixelnum = 0;
434 int ybegin = floor ((double) p_row * m_cellheight);
435 int yend = floor ((double) (p_row + 1) * m_cellheight);
436 int xbegin = floor ((double) (p_col) * m_cellwidth);
437 int xend = floor ((double) (p_col + 1) * m_cellwidth);
438 int cellw = xend - xbegin;
439 int cellh = yend - ybegin;
440 int cellarea = cellw * cellh;
441 *p_cellarea = cellarea;
442 int thresholdmotionpixelnum = floor ((double) cellarea * m_sensitivity);
444 for (int i = ybegin; i < yend; i++) {
445 for (int j = xbegin; j < xend; j++) {
447 if ((((uchar *) (m_pbwImage->imageData + m_pbwImage->widthStep * i))[j]) >
450 if (cntmotionpixelnum >= thresholdmotionpixelnum) { //we dont needs calculate anymore
451 *p_motionarea = cntmotionpixelnum;
452 return (cntmotionpixelnum / cntpixelsnum);
455 int remainingpixelsnum = cellarea - cntpixelsnum;
456 if ((cntmotionpixelnum + remainingpixelsnum) < thresholdmotionpixelnum) { //moving pixels number will be less than threshold
463 return (cntmotionpixelnum / cntpixelsnum);
467 MotionCells::calculateMotionPercentInMotionCells (motioncellidx *
468 p_motioncellsidx, int p_motioncells_count)
470 if (p_motioncells_count == 0) {
471 for (int i = 0; i < m_gridy; i++) {
472 for (int j = 0; j < m_gridx; j++) {
473 m_pCells[i][j].MotionPercent = calculateMotionPercentInCell (i, j,
474 &m_pCells[i][j].CellArea, &m_pCells[i][j].MotionArea);
475 m_pCells[i][j].hasMotion =
476 m_sensitivity < m_pCells[i][j].MotionPercent ? true : false;
477 if (m_pCells[i][j].hasMotion) {
481 mci.cell_pt1.x = floor ((double) j * m_cellwidth);
482 mci.cell_pt1.y = floor ((double) i * m_cellheight);
483 mci.cell_pt2.x = floor ((double) (j + 1) * m_cellwidth);
484 mci.cell_pt2.y = floor ((double) (i + 1) * m_cellheight);
485 int w = mci.cell_pt2.x - mci.cell_pt1.x;
486 int h = mci.cell_pt2.y - mci.cell_pt1.y;
487 mci.motioncell = cvRect (mci.cell_pt1.x, mci.cell_pt1.y, w, h);
488 m_MotionCells.push_back (mci);
493 for (int k = 0; k < p_motioncells_count; ++k) {
495 int i = p_motioncellsidx[k].lineidx;
496 int j = p_motioncellsidx[k].columnidx;
497 m_pCells[i][j].MotionPercent =
498 calculateMotionPercentInCell (i, j,
499 &m_pCells[i][j].CellArea, &m_pCells[i][j].MotionArea);
500 m_pCells[i][j].hasMotion =
501 m_pCells[i][j].MotionPercent > m_sensitivity ? true : false;
502 if (m_pCells[i][j].hasMotion) {
504 mci.lineidx = p_motioncellsidx[k].lineidx;
505 mci.colidx = p_motioncellsidx[k].columnidx;
506 mci.cell_pt1.x = floor ((double) j * m_cellwidth);
507 mci.cell_pt1.y = floor ((double) i * m_cellheight);
508 mci.cell_pt2.x = floor ((double) (j + 1) * m_cellwidth);
509 mci.cell_pt2.y = floor ((double) (i + 1) * m_cellheight);
510 int w = mci.cell_pt2.x - mci.cell_pt1.x;
511 int h = mci.cell_pt2.y - mci.cell_pt1.y;
512 mci.motioncell = cvRect (mci.cell_pt1.x, mci.cell_pt1.y, w, h);
513 m_MotionCells.push_back (mci);
520 MotionCells::performMotionMaskCoords (motionmaskcoordrect * p_motionmaskcoords,
521 int p_motionmaskcoords_count)
529 for (int i = 0; i < p_motionmaskcoords_count; i++) {
530 upperleft.x = p_motionmaskcoords[i].upper_left_x;
531 upperleft.y = p_motionmaskcoords[i].upper_left_y;
532 lowerright.x = p_motionmaskcoords[i].lower_right_x;
533 lowerright.y = p_motionmaskcoords[i].lower_right_y;
534 cvRectangle (m_pbwImage, upperleft, lowerright, CV_RGB (0, 0, 0),
540 MotionCells::performMotionMask (motioncellidx * p_motionmaskcellsidx,
541 int p_motionmaskcells_count)
543 for (int k = 0; k < p_motionmaskcells_count; k++) {
544 int beginy = p_motionmaskcellsidx[k].lineidx * m_cellheight;
545 int beginx = p_motionmaskcellsidx[k].columnidx * m_cellwidth;
547 (double) p_motionmaskcellsidx[k].columnidx * m_cellwidth + m_cellwidth;
549 (double) p_motionmaskcellsidx[k].lineidx * m_cellheight + m_cellheight;
550 for (int i = beginy; i < endy; i++)
551 for (int j = beginx; j < endx; j++) {
552 ((uchar *) (m_pbwImage->imageData + m_pbwImage->widthStep * i))[j] = 0;
557 ///BGR if we use only OpenCV
558 //RGB if we use gst+OpenCV
560 MotionCells::blendImages (IplImage * p_actFrame, IplImage * p_cellsFrame,
561 float p_alpha, float p_beta)
564 int height = p_actFrame->height;
565 int width = p_actFrame->width;
566 int step = p_actFrame->widthStep / sizeof (uchar);
567 int channels = p_actFrame->nChannels;
568 int cellstep = p_cellsFrame->widthStep / sizeof (uchar);
569 uchar *curImageData = (uchar *) p_actFrame->imageData;
570 uchar *cellImageData = (uchar *) p_cellsFrame->imageData;
572 for (int i = 0; i < height; i++)
573 for (int j = 0; j < width; j++)
574 for (int k = 0; k < channels; k++)
575 if (cellImageData[i * cellstep + j * channels + k] > 0) {
576 curImageData[i * step + j * channels + k] =
577 round ((double) curImageData[i * step + j * channels +
578 k] * p_alpha + ((double) cellImageData[i * cellstep +
579 j * channels + k] * p_beta));