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 <arpa/inet.h>
57 #include "MotionCells.h"
59 uint64_t ntohl64 (uint64_t val);
60 uint64_t htonl64 (uint64_t val);
63 ntohl64 (uint64_t val)
66 uint32_t low = (uint32_t) (val & 0x00000000FFFFFFFFLL);
67 uint32_t high = (uint32_t) ((val & 0xFFFFFFFF00000000LL) >> 32);
70 res64 = (uint64_t) high + (((uint64_t) low) << 32);
76 htonl64 (uint64_t val)
79 uint32_t low = (uint32_t) (val & 0x00000000FFFFFFFFLL);
80 uint32_t high = (uint32_t) ((val & 0xFFFFFFFF00000000LL) >> 32);
83 res64 = (uint64_t) high + (((uint64_t) low) << 32);
87 MotionCells::MotionCells ()
90 m_motioncells_idx_count = 0;
91 m_motioncellsidxcstr = NULL;
92 m_saveInDatafile = false;
96 transparencyimg = NULL;
97 m_pdifferenceImage = NULL;
99 m_initdatafilefailed = new char[BUSMSGLEN];
100 m_savedatafilefailed = new char[BUSMSGLEN];
110 MotionCells::~MotionCells ()
113 fclose (mc_savefile);
116 delete[]m_initdatafilefailed;
117 delete[]m_savedatafilefailed;
118 if (m_motioncellsidxcstr)
119 delete[]m_motioncellsidxcstr;
121 cvReleaseImage (&m_pcurFrame);
123 cvReleaseImage (&m_pprevFrame);
125 cvReleaseImage (&transparencyimg);
126 if (m_pdifferenceImage)
127 cvReleaseImage (&m_pdifferenceImage);
129 cvReleaseImage (&m_pbwImage);
133 MotionCells::performDetectionMotionCells (IplImage * p_frame,
134 double p_sensitivity, double p_framerate, int p_gridx, int p_gridy,
135 gint64 timestamp_millisec, bool p_isVisible, bool p_useAlpha,
136 int motionmaskcoord_count, motionmaskcoordrect * motionmaskcoords,
137 int motionmaskcells_count, motioncellidx * motionmaskcellsidx,
138 cellscolor motioncellscolor, int motioncells_count,
139 motioncellidx * motioncellsidx, gint64 starttime, char *p_datafile,
140 bool p_changed_datafile, int p_thickness)
145 p_framerate >= 1 ? p_framerate <= 5 ? sumframecnt = 1
146 : p_framerate <= 10 ? sumframecnt = 2
147 : p_framerate <= 15 ? sumframecnt = 3
148 : p_framerate <= 20 ? sumframecnt = 4
149 : p_framerate <= 25 ? sumframecnt = 5 : sumframecnt = 0 : sumframecnt = 0;
152 m_changed_datafile = p_changed_datafile;
153 if (m_framecnt >= sumframecnt) {
154 m_useAlpha = p_useAlpha;
157 if (m_changed_datafile) {
158 ret = initDataFile (p_datafile, starttime);
163 m_frameSize = cvGetSize (p_frame);
164 m_frameSize.width /= 2;
165 m_frameSize.height /= 2;
166 setMotionCells (m_frameSize.width, m_frameSize.height);
167 m_sensitivity = 1 - p_sensitivity;
168 m_isVisible = p_isVisible;
169 m_pcurFrame = cvCloneImage (p_frame);
170 IplImage *m_pcurgreyImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
171 IplImage *m_pprevgreyImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
172 IplImage *m_pgreyImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
173 IplImage *m_pcurDown =
174 cvCreateImage (m_frameSize, m_pcurFrame->depth, m_pcurFrame->nChannels);
175 IplImage *m_pprevDown = cvCreateImage (m_frameSize, m_pprevFrame->depth,
176 m_pprevFrame->nChannels);
177 m_pbwImage = cvCreateImage (m_frameSize, IPL_DEPTH_8U, 1);
178 cvPyrDown (m_pprevFrame, m_pprevDown);
179 cvCvtColor (m_pprevDown, m_pprevgreyImage, CV_RGB2GRAY);
180 cvPyrDown (m_pcurFrame, m_pcurDown);
181 cvCvtColor (m_pcurDown, m_pcurgreyImage, CV_RGB2GRAY);
182 m_pdifferenceImage = cvCloneImage (m_pcurgreyImage);
183 //cvSmooth(m_pcurgreyImage, m_pcurgreyImage, CV_GAUSSIAN, 3, 0);//TODO camera noise reduce,something smoothing, and rethink runningavg weights
185 //Minus the current gray frame from the 8U moving average.
186 cvAbsDiff (m_pprevgreyImage, m_pcurgreyImage, m_pdifferenceImage);
188 //Convert the image to black and white.
189 cvAdaptiveThreshold (m_pdifferenceImage, m_pbwImage, 255,
190 CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV, 7);
192 // Dilate and erode to get object blobs
193 cvDilate (m_pbwImage, m_pbwImage, NULL, 2);
194 cvErode (m_pbwImage, m_pbwImage, NULL, 2);
196 //mask-out the overlay on difference image
197 if (motionmaskcoord_count > 0)
198 performMotionMaskCoords (motionmaskcoords, motionmaskcoord_count);
199 if (motionmaskcells_count > 0)
200 performMotionMask (motionmaskcellsidx, motionmaskcells_count);
201 if (getIsNonZero (m_pbwImage)) { //detect Motion
202 GST_DEBUG ("DETECT MOTION \n");
203 if (m_MotionCells.size () > 0) //it contains previous motioncells what we used when frames dropped
204 m_MotionCells.clear ();
206 cvReleaseImage (&transparencyimg);
207 (motioncells_count > 0) ?
208 calculateMotionPercentInMotionCells (motioncellsidx,
210 : calculateMotionPercentInMotionCells (motionmaskcellsidx, 0);
212 transparencyimg = cvCreateImage (cvGetSize (p_frame), p_frame->depth, 3);
213 cvSetZero (transparencyimg);
214 if (m_motioncellsidxcstr)
215 delete[]m_motioncellsidxcstr;
216 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
217 m_motioncellsidxcstr = new char[m_motioncells_idx_count];
218 char *tmpstr = new char[MSGLEN];
219 for (int i = 0; i < MSGLEN; i++)
221 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
223 pt1.x = m_MotionCells.at (i).cell_pt1.x * 2;
224 pt1.y = m_MotionCells.at (i).cell_pt1.y * 2;
225 pt2.x = m_MotionCells.at (i).cell_pt2.x * 2;
226 pt2.y = m_MotionCells.at (i).cell_pt2.y * 2;
227 if (m_useAlpha && m_isVisible) {
228 cvRectangle (transparencyimg,
231 CV_RGB (motioncellscolor.B_channel_value,
232 motioncellscolor.G_channel_value,
233 motioncellscolor.R_channel_value), CV_FILLED);
234 } else if (m_isVisible) {
235 cvRectangle (p_frame,
238 CV_RGB (motioncellscolor.B_channel_value,
239 motioncellscolor.G_channel_value,
240 motioncellscolor.R_channel_value), p_thickness);
243 if (i < m_MotionCells.size () - 1) {
244 snprintf (tmpstr, MSGLEN, "%d:%d,", m_MotionCells.at (i).lineidx,
245 m_MotionCells.at (i).colidx);
247 snprintf (tmpstr, MSGLEN, "%d:%d", m_MotionCells.at (i).lineidx,
248 m_MotionCells.at (i).colidx);
251 strncpy (m_motioncellsidxcstr, tmpstr, m_motioncells_idx_count);
253 strcat (m_motioncellsidxcstr, tmpstr);
255 if (m_MotionCells.size () == 0)
256 strncpy (m_motioncellsidxcstr, " ", m_motioncells_idx_count);
258 if (m_useAlpha && m_isVisible) {
259 if (m_MotionCells.size () > 0)
260 blendImages (p_frame, transparencyimg, m_alpha, m_beta);
265 if (mc_savefile && m_saveInDatafile) {
266 ret = saveMotionCells (timestamp_millisec);
271 m_motioncells_idx_count = 0;
272 if (m_MotionCells.size () > 0)
273 m_MotionCells.clear ();
275 cvReleaseImage (&transparencyimg);
279 cvReleaseImage (&m_pprevFrame);
280 m_pprevFrame = cvCloneImage (m_pcurFrame);
283 cvReleaseImage (&m_pcurFrame);
284 if (m_pdifferenceImage)
285 cvReleaseImage (&m_pdifferenceImage);
287 cvReleaseImage (&m_pcurgreyImage);
288 if (m_pprevgreyImage)
289 cvReleaseImage (&m_pprevgreyImage);
291 cvReleaseImage (&m_pgreyImage);
293 cvReleaseImage (&m_pbwImage);
295 cvReleaseImage (&m_pprevDown);
297 cvReleaseImage (&m_pcurDown);
299 for (int i = 0; i < m_gridy; ++i) {
305 if (p_framerate <= 5) {
306 if (m_MotionCells.size () > 0)
307 m_MotionCells.clear ();
309 cvReleaseImage (&transparencyimg);
311 } else { //we do frame drop
312 m_motioncells_idx_count = 0;
314 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
316 pt1.x = m_MotionCells.at (i).cell_pt1.x * 2;
317 pt1.y = m_MotionCells.at (i).cell_pt1.y * 2;
318 pt2.x = m_MotionCells.at (i).cell_pt2.x * 2;
319 pt2.y = m_MotionCells.at (i).cell_pt2.y * 2;
320 if (m_useAlpha && m_isVisible) {
321 cvRectangle (transparencyimg,
324 CV_RGB (motioncellscolor.B_channel_value,
325 motioncellscolor.G_channel_value,
326 motioncellscolor.R_channel_value), CV_FILLED);
327 } else if (m_isVisible) {
328 cvRectangle (p_frame,
331 CV_RGB (motioncellscolor.B_channel_value,
332 motioncellscolor.G_channel_value,
333 motioncellscolor.R_channel_value), p_thickness);
337 if (m_useAlpha && m_isVisible) {
338 if (m_MotionCells.size () > 0)
339 blendImages (p_frame, transparencyimg, m_alpha, m_beta);
346 MotionCells::initDataFile (char *p_datafile, gint64 starttime) //p_date is increased with difference between current and previous buffer ts
349 if (strncmp (p_datafile, " ", 1)) {
350 mc_savefile = fopen (p_datafile, "w");
351 if (mc_savefile == NULL) {
352 //fprintf(stderr, "%s %d:initDataFile:fopen:%d (%s)\n", __FILE__, __LINE__, errno,
354 strncpy (m_initdatafilefailed, strerror (errno), BUSMSGLEN - 1);
355 m_initerrorcode = errno;
358 m_saveInDatafile = true;
362 bzero (&m_header, sizeof (MotionCellHeader));
363 m_header.headersize = htonl (MC_HEADER);
364 m_header.type = htonl (MC_TYPE);
365 m_header.version = htonl (MC_VERSION);
366 //it needs these bytes
368 htonl ((int) ceil (ceil (m_gridx * m_gridy / 8.0) / 4.0) * 4 +
369 sizeof (mcd.timestamp));
370 m_header.gridx = htonl (m_gridx);
371 m_header.gridy = htonl (m_gridy);
372 m_header.starttime = htonl64 (starttime);
374 snprintf (m_header.name, sizeof (m_header.name), "%s %dx%d", MC_VERSIONTEXT,
375 ntohl (m_header.gridx), ntohl (m_header.gridy));
376 m_changed_datafile = false;
381 MotionCells::saveMotionCells (gint64 timestamp_millisec)
384 MotionCellData mc_data;
385 mc_data.timestamp = htonl (timestamp_millisec);
387 //There is no datafile
388 if (mc_savefile == NULL)
391 if (ftello (mc_savefile) == 0) {
392 //cerr << "Writing out file header"<< m_header.headersize <<":" << sizeof(MotionCellHeader) << " itemsize:"
393 //<< m_header.itemsize << endl;
394 if (fwrite (&m_header, sizeof (MotionCellHeader), 1, mc_savefile) != 1) {
395 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
397 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
398 m_saveerrorcode = errno;
405 ntohl (m_header.itemsize) - sizeof (mc_data.timestamp));
406 if (mc_data.data == NULL) {
407 //fprintf(stderr, "%s %d:saveMotionCells:calloc:%d (%s)\n", __FILE__, __LINE__, errno,
409 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
410 m_saveerrorcode = errno;
414 for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
416 m_MotionCells.at (i).lineidx * ntohl (m_header.gridx) +
417 m_MotionCells.at (i).colidx;
418 int bytenum = (int) floor (bitnum / 8.0);
419 int shift = bitnum - bytenum * 8;
420 mc_data.data[bytenum] = mc_data.data[bytenum] | (1 << shift);
421 //cerr << "Motion Detected " << "line:" << m_MotionCells.at(i).lineidx << " col:" << m_MotionCells.at(i).colidx;
422 //cerr << " bitnum " << bitnum << " bytenum " << bytenum << " shift " << shift << " value " << (int)mc_data.data[bytenum] << endl;
425 if (fwrite (&mc_data.timestamp, sizeof (mc_data.timestamp), 1,
427 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
429 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
430 m_saveerrorcode = errno;
434 if (fwrite (mc_data.data,
435 ntohl (m_header.itemsize) - sizeof (mc_data.timestamp), 1,
437 //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
439 strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
440 m_saveerrorcode = errno;
449 MotionCells::calculateMotionPercentInCell (int p_row, int p_col,
450 double *p_cellarea, double *p_motionarea)
452 double cntpixelsnum = 0;
453 double cntmotionpixelnum = 0;
455 int ybegin = floor ((double) p_row * m_cellheight);
456 int yend = floor ((double) (p_row + 1) * m_cellheight);
457 int xbegin = floor ((double) (p_col) * m_cellwidth);
458 int xend = floor ((double) (p_col + 1) * m_cellwidth);
459 int cellw = xend - xbegin;
460 int cellh = yend - ybegin;
461 int cellarea = cellw * cellh;
462 *p_cellarea = cellarea;
463 int thresholdmotionpixelnum = floor ((double) cellarea * m_sensitivity);
465 for (int i = ybegin; i < yend; i++) {
466 for (int j = xbegin; j < xend; j++) {
468 if ((((uchar *) (m_pbwImage->imageData + m_pbwImage->widthStep * i))[j]) >
471 if (cntmotionpixelnum >= thresholdmotionpixelnum) { //we dont needs calculate anymore
472 *p_motionarea = cntmotionpixelnum;
473 return (cntmotionpixelnum / cntpixelsnum);
476 int remainingpixelsnum = cellarea - cntpixelsnum;
477 if ((cntmotionpixelnum + remainingpixelsnum) < thresholdmotionpixelnum) { //moving pixels number will be less than threshold
484 return (cntmotionpixelnum / cntpixelsnum);
488 MotionCells::calculateMotionPercentInMotionCells (motioncellidx *
489 p_motioncellsidx, int p_motioncells_count)
491 if (p_motioncells_count == 0) {
492 for (int i = 0; i < m_gridy; i++) {
493 for (int j = 0; j < m_gridx; j++) {
494 m_pCells[i][j].MotionPercent = calculateMotionPercentInCell (i, j,
495 &m_pCells[i][j].CellArea, &m_pCells[i][j].MotionArea);
496 m_pCells[i][j].hasMotion =
497 m_sensitivity < m_pCells[i][j].MotionPercent ? true : false;
498 if (m_pCells[i][j].hasMotion) {
502 mci.cell_pt1.x = floor ((double) j * m_cellwidth);
503 mci.cell_pt1.y = floor ((double) i * m_cellheight);
504 mci.cell_pt2.x = floor ((double) (j + 1) * m_cellwidth);
505 mci.cell_pt2.y = floor ((double) (i + 1) * m_cellheight);
506 int w = mci.cell_pt2.x - mci.cell_pt1.x;
507 int h = mci.cell_pt2.y - mci.cell_pt1.y;
508 mci.motioncell = cvRect (mci.cell_pt1.x, mci.cell_pt1.y, w, h);
509 m_MotionCells.push_back (mci);
514 for (int k = 0; k < p_motioncells_count; ++k) {
516 int i = p_motioncellsidx[k].lineidx;
517 int j = p_motioncellsidx[k].columnidx;
518 m_pCells[i][j].MotionPercent =
519 calculateMotionPercentInCell (i, j,
520 &m_pCells[i][j].CellArea, &m_pCells[i][j].MotionArea);
521 m_pCells[i][j].hasMotion =
522 m_pCells[i][j].MotionPercent > m_sensitivity ? true : false;
523 if (m_pCells[i][j].hasMotion) {
525 mci.lineidx = p_motioncellsidx[k].lineidx;
526 mci.colidx = p_motioncellsidx[k].columnidx;
527 mci.cell_pt1.x = floor ((double) j * m_cellwidth);
528 mci.cell_pt1.y = floor ((double) i * m_cellheight);
529 mci.cell_pt2.x = floor ((double) (j + 1) * m_cellwidth);
530 mci.cell_pt2.y = floor ((double) (i + 1) * m_cellheight);
531 int w = mci.cell_pt2.x - mci.cell_pt1.x;
532 int h = mci.cell_pt2.y - mci.cell_pt1.y;
533 mci.motioncell = cvRect (mci.cell_pt1.x, mci.cell_pt1.y, w, h);
534 m_MotionCells.push_back (mci);
541 MotionCells::performMotionMaskCoords (motionmaskcoordrect * p_motionmaskcoords,
542 int p_motionmaskcoords_count)
550 for (int i = 0; i < p_motionmaskcoords_count; i++) {
551 upperleft.x = p_motionmaskcoords[i].upper_left_x;
552 upperleft.y = p_motionmaskcoords[i].upper_left_y;
553 lowerright.x = p_motionmaskcoords[i].lower_right_x;
554 lowerright.y = p_motionmaskcoords[i].lower_right_y;
555 cvRectangle (m_pbwImage, upperleft, lowerright, CV_RGB (0, 0, 0),
561 MotionCells::performMotionMask (motioncellidx * p_motionmaskcellsidx,
562 int p_motionmaskcells_count)
564 for (int k = 0; k < p_motionmaskcells_count; k++) {
565 int beginy = p_motionmaskcellsidx[k].lineidx * m_cellheight;
566 int beginx = p_motionmaskcellsidx[k].columnidx * m_cellwidth;
568 (double) p_motionmaskcellsidx[k].columnidx * m_cellwidth + m_cellwidth;
570 (double) p_motionmaskcellsidx[k].lineidx * m_cellheight + m_cellheight;
571 for (int i = beginy; i < endy; i++)
572 for (int j = beginx; j < endx; j++) {
573 ((uchar *) (m_pbwImage->imageData + m_pbwImage->widthStep * i))[j] = 0;
578 ///BGR if we use only OpenCV
579 //RGB if we use gst+OpenCV
581 MotionCells::blendImages (IplImage * p_actFrame, IplImage * p_cellsFrame,
582 float p_alpha, float p_beta)
585 int height = p_actFrame->height;
586 int width = p_actFrame->width;
587 int step = p_actFrame->widthStep / sizeof (uchar);
588 int channels = p_actFrame->nChannels;
589 int cellstep = p_cellsFrame->widthStep / sizeof (uchar);
590 uchar *curImageData = (uchar *) p_actFrame->imageData;
591 uchar *cellImageData = (uchar *) p_cellsFrame->imageData;
593 for (int i = 0; i < height; i++)
594 for (int j = 0; j < width; j++)
595 for (int k = 0; k < channels; k++)
596 if (cellImageData[i * cellstep + j * channels + k] > 0) {
597 curImageData[i * step + j * channels + k] =
598 round ((double) curImageData[i * step + j * channels +
599 k] * p_alpha + ((double) cellImageData[i * cellstep +
600 j * channels + k] * p_beta));