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.
45 /* This breaks the build for reasons that aren't entirely clear to me yet */
47 //#ifdef HAVE_CONFIG_H
56 #include "MotionCells.h"
57 #include <opencv2/imgproc/imgproc_c.h>
59 MotionCells::MotionCells ()
62 m_motioncells_idx_count = 0;
63 m_motioncellsidxcstr = NULL;
64 m_saveInDatafile = false;
68 transparencyimg = NULL;
69 m_pdifferenceImage = NULL;
71 m_initdatafilefailed = new char[BUSMSGLEN];
72 m_savedatafilefailed = new char[BUSMSGLEN];
87 MotionCells::~MotionCells ()
93 delete[]m_initdatafilefailed;
94 delete[]m_savedatafilefailed;
95 if (m_motioncellsidxcstr)
96 delete[]m_motioncellsidxcstr;
98 cvReleaseImage (&m_pcurFrame);
100 cvReleaseImage (&m_pprevFrame);
102 cvReleaseImage (&transparencyimg);
103 if (m_pdifferenceImage)
104 cvReleaseImage (&m_pdifferenceImage);
106 cvReleaseImage (&m_pbwImage);
110 MotionCells::performDetectionMotionCells (IplImage * p_frame,
111 double p_sensitivity, double p_framerate, int p_gridx, int p_gridy,
112 gint64 timestamp_millisec, bool p_isVisible, bool p_useAlpha,
113 int motionmaskcoord_count, motionmaskcoordrect * motionmaskcoords,
114 int motionmaskcells_count, motioncellidx * motionmaskcellsidx,
115 cellscolor motioncellscolor, int motioncells_count,
116 motioncellidx * motioncellsidx, gint64 starttime, char *p_datafile,
117 bool p_changed_datafile, int p_thickness)
122 p_framerate >= 1 ? p_framerate <= 5 ? sumframecnt = 1
123 : p_framerate <= 10 ? sumframecnt = 2
124 : p_framerate <= 15 ? sumframecnt = 3
125 : p_framerate <= 20 ? sumframecnt = 4
126 : p_framerate <= 25 ? sumframecnt = 5
127 : p_framerate <= 30 ? sumframecnt = 6 : sumframecnt = 0 : sumframecnt = 0;
130 m_changed_datafile = p_changed_datafile;
131 if (m_framecnt >= sumframecnt) {
132 m_useAlpha = p_useAlpha;
135 if (m_changed_datafile) {
136 ret = initDataFile (p_datafile, starttime);
141 m_frameSize = cvGetSize (p_frame);
142 m_frameSize.width /= 2;
143 m_frameSize.height /= 2;
144 setMotionCells (m_frameSize.width, m_frameSize.height);
145 m_sensitivity = 1 - p_sensitivity;
146 m_isVisible = p_isVisible;
147 m_pcurFrame = cvCloneImage (p_frame);
148 IplImage *m_pcurgreyImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
149 IplImage *m_pprevgreyImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
150 IplImage *m_pgreyImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
151 IplImage *m_pcurDown =
152 cvCreateImage (m_frameSize, m_pcurFrame->depth, m_pcurFrame->nChannels);
153 IplImage *m_pprevDown = cvCreateImage (m_frameSize, m_pprevFrame->depth,
154 m_pprevFrame->nChannels);
155 m_pbwImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
156 cvPyrDown (m_pprevFrame, m_pprevDown);
157 cvCvtColor (m_pprevDown, m_pprevgreyImage, CV_RGB2GRAY);
158 cvPyrDown (m_pcurFrame, m_pcurDown);
159 cvCvtColor (m_pcurDown, m_pcurgreyImage, CV_RGB2GRAY);
160 m_pdifferenceImage = cvCloneImage (m_pcurgreyImage);
161 //cvSmooth(m_pcurgreyImage, m_pcurgreyImage, CV_GAUSSIAN, 3, 0);//TODO camera noise reduce,something smoothing, and rethink runningavg weights
163 //Minus the current gray frame from the 8U moving average.
164 cvAbsDiff (m_pprevgreyImage, m_pcurgreyImage, m_pdifferenceImage);
166 //Convert the image to black and white.
167 cvAdaptiveThreshold (m_pdifferenceImage, m_pbwImage, 255,
168 CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV, 7);
170 // Dilate and erode to get object blobs
171 cvDilate (m_pbwImage, m_pbwImage, NULL, 2);
172 cvErode (m_pbwImage, m_pbwImage, NULL, 2);
174 //mask-out the overlay on difference image
175 if (motionmaskcoord_count > 0)
176 performMotionMaskCoords (motionmaskcoords, motionmaskcoord_count);
177 if (motionmaskcells_count > 0)
178 performMotionMask (motionmaskcellsidx, motionmaskcells_count);
179 if (getIsNonZero (m_pbwImage)) { //detect Motion
180 if (m_MotionCells.size () > 0) //it contains previous motioncells what we used when frames dropped
181 m_MotionCells.clear ();
183 cvReleaseImage (&transparencyimg);
184 (motioncells_count > 0) ?
185 calculateMotionPercentInMotionCells (motioncellsidx,
187 : calculateMotionPercentInMotionCells (motionmaskcellsidx, 0);
189 transparencyimg = cvCreateImage (cvGetSize (p_frame), p_frame->depth, 3);
190 cvSetZero (transparencyimg);
191 if (m_motioncellsidxcstr)
192 delete[]m_motioncellsidxcstr;
193 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
194 m_motioncellsidxcstr = new char[m_motioncells_idx_count];
195 char *tmpstr = new char[MSGLEN];
196 for (int i = 0; i < MSGLEN; i++)
198 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
200 pt1.x = m_MotionCells.at (i).cell_pt1.x * 2;
201 pt1.y = m_MotionCells.at (i).cell_pt1.y * 2;
202 pt2.x = m_MotionCells.at (i).cell_pt2.x * 2;
203 pt2.y = m_MotionCells.at (i).cell_pt2.y * 2;
204 if (m_useAlpha && m_isVisible) {
205 cvRectangle (transparencyimg,
208 CV_RGB (motioncellscolor.B_channel_value,
209 motioncellscolor.G_channel_value,
210 motioncellscolor.R_channel_value), CV_FILLED);
211 } else if (m_isVisible) {
212 cvRectangle (p_frame,
215 CV_RGB (motioncellscolor.B_channel_value,
216 motioncellscolor.G_channel_value,
217 motioncellscolor.R_channel_value), p_thickness);
220 if (i < m_MotionCells.size () - 1) {
221 snprintf (tmpstr, MSGLEN, "%d:%d,", m_MotionCells.at (i).lineidx,
222 m_MotionCells.at (i).colidx);
224 snprintf (tmpstr, MSGLEN, "%d:%d", m_MotionCells.at (i).lineidx,
225 m_MotionCells.at (i).colidx);
228 strncpy (m_motioncellsidxcstr, tmpstr, m_motioncells_idx_count);
230 strcat (m_motioncellsidxcstr, tmpstr);
232 if (m_MotionCells.size () == 0)
233 strncpy (m_motioncellsidxcstr, " ", m_motioncells_idx_count);
235 if (m_useAlpha && m_isVisible) {
236 if (m_MotionCells.size () > 0)
237 blendImages (p_frame, transparencyimg, m_alpha, m_beta);
242 if (mc_savefile && m_saveInDatafile) {
243 ret = saveMotionCells (timestamp_millisec);
248 m_motioncells_idx_count = 0;
249 if (m_MotionCells.size () > 0)
250 m_MotionCells.clear ();
252 cvReleaseImage (&transparencyimg);
256 cvReleaseImage (&m_pprevFrame);
257 m_pprevFrame = cvCloneImage (m_pcurFrame);
260 cvReleaseImage (&m_pcurFrame);
261 if (m_pdifferenceImage)
262 cvReleaseImage (&m_pdifferenceImage);
264 cvReleaseImage (&m_pcurgreyImage);
265 if (m_pprevgreyImage)
266 cvReleaseImage (&m_pprevgreyImage);
268 cvReleaseImage (&m_pgreyImage);
270 cvReleaseImage (&m_pbwImage);
272 cvReleaseImage (&m_pprevDown);
274 cvReleaseImage (&m_pcurDown);
276 for (int i = 0; i < m_gridy; ++i) {
282 if (p_framerate <= 5) {
283 if (m_MotionCells.size () > 0)
284 m_MotionCells.clear ();
286 cvReleaseImage (&transparencyimg);
288 } else { //we do frame drop
289 m_motioncells_idx_count = 0;
291 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
293 pt1.x = m_MotionCells.at (i).cell_pt1.x * 2;
294 pt1.y = m_MotionCells.at (i).cell_pt1.y * 2;
295 pt2.x = m_MotionCells.at (i).cell_pt2.x * 2;
296 pt2.y = m_MotionCells.at (i).cell_pt2.y * 2;
297 if (m_useAlpha && m_isVisible) {
298 cvRectangle (transparencyimg,
301 CV_RGB (motioncellscolor.B_channel_value,
302 motioncellscolor.G_channel_value,
303 motioncellscolor.R_channel_value), CV_FILLED);
304 } else if (m_isVisible) {
305 cvRectangle (p_frame,
308 CV_RGB (motioncellscolor.B_channel_value,
309 motioncellscolor.G_channel_value,
310 motioncellscolor.R_channel_value), p_thickness);
314 if (m_useAlpha && m_isVisible) {
315 if (m_MotionCells.size () > 0)
316 blendImages (p_frame, transparencyimg, m_alpha, m_beta);
323 MotionCells::initDataFile (char *p_datafile, gint64 starttime) //p_date is increased with difference between current and previous buffer ts
326 if (strncmp (p_datafile, " ", 1)) {
327 mc_savefile = fopen (p_datafile, "w");
328 if (mc_savefile == NULL) {
329 //fprintf(stderr, "%s %d:initDataFile:fopen:%d (%s)\n", __FILE__, __LINE__, errno,
331 strncpy (m_initdatafilefailed, strerror (errno), BUSMSGLEN - 1);
332 m_initerrorcode = errno;
335 m_saveInDatafile = true;
339 memset (&m_header, 0, sizeof (MotionCellHeader));
340 m_header.headersize = GINT32_TO_BE (MC_HEADER);
341 m_header.type = GINT32_TO_BE (MC_TYPE);
342 m_header.version = GINT32_TO_BE (MC_VERSION);
343 //it needs these bytes
345 GINT32_TO_BE ((int) ceil (ceil (m_gridx * m_gridy / 8.0) / 4.0) * 4 +
346 sizeof (mcd.timestamp));
347 m_header.gridx = GINT32_TO_BE (m_gridx);
348 m_header.gridy = GINT32_TO_BE (m_gridy);
349 m_header.starttime = GINT64_TO_BE (starttime);
351 snprintf (m_header.name, sizeof (m_header.name), "%s %dx%d", MC_VERSIONTEXT,
352 GINT32_FROM_BE (m_header.gridx), GINT32_FROM_BE (m_header.gridy));
353 m_changed_datafile = false;
358 MotionCells::saveMotionCells (gint64 timestamp_millisec)
361 MotionCellData mc_data;
362 mc_data.timestamp = GINT32_TO_BE (timestamp_millisec);
364 //There is no datafile
365 if (mc_savefile == NULL)
368 if (ftello (mc_savefile) == 0) {
369 //cerr << "Writing out file header"<< m_header.headersize <<":" << sizeof(MotionCellHeader) << " itemsize:"
370 //<< m_header.itemsize << endl;
371 if (fwrite (&m_header, sizeof (MotionCellHeader), 1, mc_savefile) != 1) {
372 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
374 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
375 m_saveerrorcode = errno;
382 GINT32_FROM_BE (m_header.itemsize) - sizeof (mc_data.timestamp));
383 if (mc_data.data == NULL) {
384 //fprintf(stderr, "%s %d:saveMotionCells:calloc:%d (%s)\n", __FILE__, __LINE__, errno,
386 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
387 m_saveerrorcode = errno;
391 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
393 m_MotionCells.at (i).lineidx * GINT32_FROM_BE (m_header.gridx) +
394 m_MotionCells.at (i).colidx;
395 int bytenum = (int) floor (bitnum / 8.0);
396 int shift = bitnum - bytenum * 8;
397 mc_data.data[bytenum] = mc_data.data[bytenum] | (1 << shift);
398 //cerr << "Motion Detected " << "line:" << m_MotionCells.at(i).lineidx << " col:" << m_MotionCells.at(i).colidx;
399 //cerr << " bitnum " << bitnum << " bytenum " << bytenum << " shift " << shift << " value " << (int)mc_data.data[bytenum] << endl;
402 if (fwrite (&mc_data.timestamp, sizeof (mc_data.timestamp), 1,
404 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
406 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
407 m_saveerrorcode = errno;
411 if (fwrite (mc_data.data,
412 GINT32_FROM_BE (m_header.itemsize) - sizeof (mc_data.timestamp), 1,
414 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
416 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
417 m_saveerrorcode = errno;
426 MotionCells::calculateMotionPercentInCell (int p_row, int p_col,
427 double *p_cellarea, double *p_motionarea)
429 double cntpixelsnum = 0;
430 double cntmotionpixelnum = 0;
432 int ybegin = floor ((double) p_row * m_cellheight);
433 int yend = floor ((double) (p_row + 1) * m_cellheight);
434 int xbegin = floor ((double) (p_col) * m_cellwidth);
435 int xend = floor ((double) (p_col + 1) * m_cellwidth);
436 int cellw = xend - xbegin;
437 int cellh = yend - ybegin;
438 int cellarea = cellw * cellh;
439 *p_cellarea = cellarea;
440 int thresholdmotionpixelnum = floor ((double) cellarea * m_sensitivity);
442 for (int i = ybegin; i < yend; i++) {
443 for (int j = xbegin; j < xend; j++) {
445 if ((((uchar *) (m_pbwImage->imageData + m_pbwImage->widthStep * i))[j]) >
448 if (cntmotionpixelnum >= thresholdmotionpixelnum) { //we dont needs calculate anymore
449 *p_motionarea = cntmotionpixelnum;
450 return (cntmotionpixelnum / cntpixelsnum);
453 int remainingpixelsnum = cellarea - cntpixelsnum;
454 if ((cntmotionpixelnum + remainingpixelsnum) < thresholdmotionpixelnum) { //moving pixels number will be less than threshold
461 return (cntmotionpixelnum / cntpixelsnum);
465 MotionCells::calculateMotionPercentInMotionCells (motioncellidx *
466 p_motioncellsidx, int p_motioncells_count)
468 if (p_motioncells_count == 0) {
469 for (int i = 0; i < m_gridy; i++) {
470 for (int j = 0; j < m_gridx; j++) {
471 m_pCells[i][j].MotionPercent = calculateMotionPercentInCell (i, j,
472 &m_pCells[i][j].CellArea, &m_pCells[i][j].MotionArea);
473 m_pCells[i][j].hasMotion =
474 m_sensitivity < m_pCells[i][j].MotionPercent ? true : false;
475 if (m_pCells[i][j].hasMotion) {
479 mci.cell_pt1.x = floor ((double) j * m_cellwidth);
480 mci.cell_pt1.y = floor ((double) i * m_cellheight);
481 mci.cell_pt2.x = floor ((double) (j + 1) * m_cellwidth);
482 mci.cell_pt2.y = floor ((double) (i + 1) * m_cellheight);
483 int w = mci.cell_pt2.x - mci.cell_pt1.x;
484 int h = mci.cell_pt2.y - mci.cell_pt1.y;
485 mci.motioncell = cvRect (mci.cell_pt1.x, mci.cell_pt1.y, w, h);
486 m_MotionCells.push_back (mci);
491 for (int k = 0; k < p_motioncells_count; ++k) {
493 int i = p_motioncellsidx[k].lineidx;
494 int j = p_motioncellsidx[k].columnidx;
495 m_pCells[i][j].MotionPercent =
496 calculateMotionPercentInCell (i, j,
497 &m_pCells[i][j].CellArea, &m_pCells[i][j].MotionArea);
498 m_pCells[i][j].hasMotion =
499 m_pCells[i][j].MotionPercent > m_sensitivity ? true : false;
500 if (m_pCells[i][j].hasMotion) {
502 mci.lineidx = p_motioncellsidx[k].lineidx;
503 mci.colidx = p_motioncellsidx[k].columnidx;
504 mci.cell_pt1.x = floor ((double) j * m_cellwidth);
505 mci.cell_pt1.y = floor ((double) i * m_cellheight);
506 mci.cell_pt2.x = floor ((double) (j + 1) * m_cellwidth);
507 mci.cell_pt2.y = floor ((double) (i + 1) * m_cellheight);
508 int w = mci.cell_pt2.x - mci.cell_pt1.x;
509 int h = mci.cell_pt2.y - mci.cell_pt1.y;
510 mci.motioncell = cvRect (mci.cell_pt1.x, mci.cell_pt1.y, w, h);
511 m_MotionCells.push_back (mci);
518 MotionCells::performMotionMaskCoords (motionmaskcoordrect * p_motionmaskcoords,
519 int p_motionmaskcoords_count)
527 for (int i = 0; i < p_motionmaskcoords_count; i++) {
528 upperleft.x = p_motionmaskcoords[i].upper_left_x;
529 upperleft.y = p_motionmaskcoords[i].upper_left_y;
530 lowerright.x = p_motionmaskcoords[i].lower_right_x;
531 lowerright.y = p_motionmaskcoords[i].lower_right_y;
532 cvRectangle (m_pbwImage, upperleft, lowerright, CV_RGB (0, 0, 0),
538 MotionCells::performMotionMask (motioncellidx * p_motionmaskcellsidx,
539 int p_motionmaskcells_count)
541 for (int k = 0; k < p_motionmaskcells_count; k++) {
542 int beginy = p_motionmaskcellsidx[k].lineidx * m_cellheight;
543 int beginx = p_motionmaskcellsidx[k].columnidx * m_cellwidth;
545 (double) p_motionmaskcellsidx[k].columnidx * m_cellwidth + m_cellwidth;
547 (double) p_motionmaskcellsidx[k].lineidx * m_cellheight + m_cellheight;
548 for (int i = beginy; i < endy; i++)
549 for (int j = beginx; j < endx; j++) {
550 ((uchar *) (m_pbwImage->imageData + m_pbwImage->widthStep * i))[j] = 0;
555 ///BGR if we use only OpenCV
556 //RGB if we use gst+OpenCV
558 MotionCells::blendImages (IplImage * p_actFrame, IplImage * p_cellsFrame,
559 float p_alpha, float p_beta)
562 int height = p_actFrame->height;
563 int width = p_actFrame->width;
564 int step = p_actFrame->widthStep / sizeof (uchar);
565 int channels = p_actFrame->nChannels;
566 int cellstep = p_cellsFrame->widthStep / sizeof (uchar);
567 uchar *curImageData = (uchar *) p_actFrame->imageData;
568 uchar *cellImageData = (uchar *) p_cellsFrame->imageData;
570 for (int i = 0; i < height; i++)
571 for (int j = 0; j < width; j++)
572 for (int k = 0; k < channels; k++)
573 if (cellImageData[i * cellstep + j * channels + k] > 0) {
574 curImageData[i * step + j * channels + k] =
575 round ((double) curImageData[i * step + j * channels +
576 k] * p_alpha + ((double) cellImageData[i * cellstep +
577 j * channels + k] * p_beta));