motioncells: fully construct MotionCells
[platform/upstream/gstreamer.git] / ext / opencv / MotionCells.cpp
1 /*
2  * GStreamer
3  * Copyright (C) 2011 Robert Jobbagy <jobbagy.robert@gmail.com>
4  * Copyright (C) 2011 Nicola Murino <nicola.murino@gmail.com>
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  *
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
27  * mentioned above:
28  *
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.
33  *
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.
38  *
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.
43  */
44
45 /* This breaks the build for reasons that aren't entirely clear to me yet */
46 #if 0
47 //#ifdef HAVE_CONFIG_H
48 //#include "config.h"
49 //#endif
50 #endif
51
52 #include <errno.h>
53 #include "MotionCells.h"
54 #include <opencv2/imgproc/imgproc_c.h>
55
56 MotionCells::MotionCells ()
57 {
58   m_framecnt = 0;
59   m_motioncells_idx_count = 0;
60   m_motioncellsidxcstr = NULL;
61   m_saveInDatafile = false;
62   mc_savefile = NULL;
63   m_pcurFrame = NULL;
64   m_pprevFrame = NULL;
65   transparencyimg = NULL;
66   m_pdifferenceImage = NULL;
67   m_pbwImage = NULL;
68   m_initdatafilefailed = new char[BUSMSGLEN];
69   m_savedatafilefailed = new char[BUSMSGLEN];
70   m_initerrorcode = 0;
71   m_saveerrorcode = 0;
72   m_alpha = 0.5;
73   m_beta = 0.5;
74   m_useAlpha = false;
75   m_isVisible = false;
76   m_pCells = NULL;
77   m_gridx = 0;
78   m_gridy = 0;
79   m_cellwidth = 0;
80   m_cellheight = 0;
81   m_sensitivity = 0;
82
83   memset (&m_header, 0, sizeof (MotionCellHeader));
84   m_header.headersize = GINT32_TO_BE (MC_HEADER);
85   m_header.type = GINT32_TO_BE (MC_TYPE);
86   m_header.version = GINT32_TO_BE (MC_VERSION);
87   m_header.itemsize = 0;
88   m_header.gridx = 0;
89   m_header.gridy = 0;
90   m_header.starttime = 0;
91 }
92
93 MotionCells::~MotionCells ()
94 {
95   if (mc_savefile) {
96     fclose (mc_savefile);
97     mc_savefile = NULL;
98   }
99   delete[]m_initdatafilefailed;
100   delete[]m_savedatafilefailed;
101   if (m_motioncellsidxcstr)
102     delete[]m_motioncellsidxcstr;
103   if (m_pcurFrame)
104     cvReleaseImage (&m_pcurFrame);
105   if (m_pprevFrame)
106     cvReleaseImage (&m_pprevFrame);
107   if (transparencyimg)
108     cvReleaseImage (&transparencyimg);
109   if (m_pdifferenceImage)
110     cvReleaseImage (&m_pdifferenceImage);
111   if (m_pbwImage)
112     cvReleaseImage (&m_pbwImage);
113 }
114
115 int
116 MotionCells::performDetectionMotionCells (IplImage * p_frame,
117     double p_sensitivity, double p_framerate, int p_gridx, int p_gridy,
118     gint64 timestamp_millisec, bool p_isVisible, bool p_useAlpha,
119     int motionmaskcoord_count, motionmaskcoordrect * motionmaskcoords,
120     int motionmaskcells_count, motioncellidx * motionmaskcellsidx,
121     cellscolor motioncellscolor, int motioncells_count,
122     motioncellidx * motioncellsidx, gint64 starttime, char *p_datafile,
123     bool p_changed_datafile, int p_thickness)
124 {
125
126   int sumframecnt = 0;
127   int ret = 0;
128   CvSize frameSize;
129
130   p_framerate >= 1 ? p_framerate <= 5 ? sumframecnt = 1
131       : p_framerate <= 10 ? sumframecnt = 2
132       : p_framerate <= 15 ? sumframecnt = 3
133       : p_framerate <= 20 ? sumframecnt = 4
134       : p_framerate <= 25 ? sumframecnt = 5
135       : p_framerate <= 30 ? sumframecnt = 6 : sumframecnt = 0 : sumframecnt = 0;
136
137   m_framecnt++;
138   m_changed_datafile = p_changed_datafile;
139   if (m_framecnt >= sumframecnt) {
140     m_useAlpha = p_useAlpha;
141     m_gridx = p_gridx;
142     m_gridy = p_gridy;
143     if (m_changed_datafile) {
144       ret = initDataFile (p_datafile, starttime);
145       if (ret != 0)
146         return ret;
147     }
148
149     frameSize = cvGetSize (p_frame);
150     frameSize.width /= 2;
151     frameSize.height /= 2;
152     setMotionCells (frameSize.width, frameSize.height);
153     m_sensitivity = 1 - p_sensitivity;
154     m_isVisible = p_isVisible;
155     m_pcurFrame = cvCloneImage (p_frame);
156     IplImage *m_pcurgreyImage = cvCreateImage (frameSize, IPL_DEPTH_8U, 1);
157     IplImage *m_pprevgreyImage = cvCreateImage (frameSize, IPL_DEPTH_8U, 1);
158     IplImage *m_pgreyImage = cvCreateImage (frameSize, IPL_DEPTH_8U, 1);
159     IplImage *m_pcurDown =
160         cvCreateImage (frameSize, m_pcurFrame->depth, m_pcurFrame->nChannels);
161     IplImage *m_pprevDown = cvCreateImage (frameSize, m_pprevFrame->depth,
162         m_pprevFrame->nChannels);
163     m_pbwImage = cvCreateImage (frameSize, IPL_DEPTH_8U, 1);
164     cvPyrDown (m_pprevFrame, m_pprevDown);
165     cvCvtColor (m_pprevDown, m_pprevgreyImage, CV_RGB2GRAY);
166     cvPyrDown (m_pcurFrame, m_pcurDown);
167     cvCvtColor (m_pcurDown, m_pcurgreyImage, CV_RGB2GRAY);
168     m_pdifferenceImage = cvCloneImage (m_pcurgreyImage);
169     //cvSmooth(m_pcurgreyImage, m_pcurgreyImage, CV_GAUSSIAN, 3, 0);//TODO camera noise reduce,something smoothing, and rethink runningavg weights
170
171     //Minus the current gray frame from the 8U moving average.
172     cvAbsDiff (m_pprevgreyImage, m_pcurgreyImage, m_pdifferenceImage);
173
174     //Convert the image to black and white.
175     cvAdaptiveThreshold (m_pdifferenceImage, m_pbwImage, 255,
176         CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV, 7);
177
178     // Dilate and erode to get object blobs
179     cvDilate (m_pbwImage, m_pbwImage, NULL, 2);
180     cvErode (m_pbwImage, m_pbwImage, NULL, 2);
181
182     //mask-out the overlay on difference image
183     if (motionmaskcoord_count > 0)
184       performMotionMaskCoords (motionmaskcoords, motionmaskcoord_count);
185     if (motionmaskcells_count > 0)
186       performMotionMask (motionmaskcellsidx, motionmaskcells_count);
187     if (getIsNonZero (m_pbwImage)) {    //detect Motion
188       if (m_MotionCells.size () > 0)    //it contains previous motioncells what we used when frames dropped
189         m_MotionCells.clear ();
190       if (transparencyimg)
191         cvReleaseImage (&transparencyimg);
192       (motioncells_count > 0) ?
193           calculateMotionPercentInMotionCells (motioncellsidx,
194           motioncells_count)
195           : calculateMotionPercentInMotionCells (motionmaskcellsidx, 0);
196
197       transparencyimg = cvCreateImage (cvGetSize (p_frame), p_frame->depth, 3);
198       cvSetZero (transparencyimg);
199       if (m_motioncellsidxcstr)
200         delete[]m_motioncellsidxcstr;
201       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
202       m_motioncellsidxcstr = new char[m_motioncells_idx_count];
203       char *tmpstr = new char[MSGLEN];
204       for (int i = 0; i < MSGLEN; i++)
205         tmpstr[i] = ' ';
206       for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
207         CvPoint pt1, pt2;
208         pt1.x = m_MotionCells.at (i).cell_pt1.x * 2;
209         pt1.y = m_MotionCells.at (i).cell_pt1.y * 2;
210         pt2.x = m_MotionCells.at (i).cell_pt2.x * 2;
211         pt2.y = m_MotionCells.at (i).cell_pt2.y * 2;
212         if (m_useAlpha && m_isVisible) {
213           cvRectangle (transparencyimg,
214               pt1,
215               pt2,
216               CV_RGB (motioncellscolor.B_channel_value,
217                   motioncellscolor.G_channel_value,
218                   motioncellscolor.R_channel_value), CV_FILLED);
219         } else if (m_isVisible) {
220           cvRectangle (p_frame,
221               pt1,
222               pt2,
223               CV_RGB (motioncellscolor.B_channel_value,
224                   motioncellscolor.G_channel_value,
225                   motioncellscolor.R_channel_value), p_thickness);
226         }
227
228         if (i < m_MotionCells.size () - 1) {
229           snprintf (tmpstr, MSGLEN, "%d:%d,", m_MotionCells.at (i).lineidx,
230               m_MotionCells.at (i).colidx);
231         } else {
232           snprintf (tmpstr, MSGLEN, "%d:%d", m_MotionCells.at (i).lineidx,
233               m_MotionCells.at (i).colidx);
234         }
235         if (i == 0)
236           strncpy (m_motioncellsidxcstr, tmpstr, m_motioncells_idx_count);
237         else
238           strcat (m_motioncellsidxcstr, tmpstr);
239       }
240       if (m_MotionCells.size () == 0)
241         strncpy (m_motioncellsidxcstr, " ", m_motioncells_idx_count);
242
243       if (m_useAlpha && m_isVisible) {
244         if (m_MotionCells.size () > 0)
245           blendImages (p_frame, transparencyimg, m_alpha, m_beta);
246       }
247
248       delete[]tmpstr;
249
250       if (mc_savefile && m_saveInDatafile) {
251         ret = saveMotionCells (timestamp_millisec);
252         if (ret != 0)
253           return ret;
254       }
255     } else {
256       m_motioncells_idx_count = 0;
257       if (m_MotionCells.size () > 0)
258         m_MotionCells.clear ();
259       if (transparencyimg)
260         cvReleaseImage (&transparencyimg);
261     }
262
263     if (m_pprevFrame)
264       cvReleaseImage (&m_pprevFrame);
265     m_pprevFrame = cvCloneImage (m_pcurFrame);
266     m_framecnt = 0;
267     if (m_pcurFrame)
268       cvReleaseImage (&m_pcurFrame);
269     if (m_pdifferenceImage)
270       cvReleaseImage (&m_pdifferenceImage);
271     if (m_pcurgreyImage)
272       cvReleaseImage (&m_pcurgreyImage);
273     if (m_pprevgreyImage)
274       cvReleaseImage (&m_pprevgreyImage);
275     if (m_pgreyImage)
276       cvReleaseImage (&m_pgreyImage);
277     if (m_pbwImage)
278       cvReleaseImage (&m_pbwImage);
279     if (m_pprevDown)
280       cvReleaseImage (&m_pprevDown);
281     if (m_pcurDown)
282       cvReleaseImage (&m_pcurDown);
283     if (m_pCells) {
284       for (int i = 0; i < m_gridy; ++i) {
285         delete[]m_pCells[i];
286       }
287       delete[]m_pCells;
288     }
289
290     if (p_framerate <= 5) {
291       if (m_MotionCells.size () > 0)
292         m_MotionCells.clear ();
293       if (transparencyimg)
294         cvReleaseImage (&transparencyimg);
295     }
296   } else {                      //we do frame drop
297     m_motioncells_idx_count = 0;
298     ret = -2;
299     for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
300       CvPoint pt1, pt2;
301       pt1.x = m_MotionCells.at (i).cell_pt1.x * 2;
302       pt1.y = m_MotionCells.at (i).cell_pt1.y * 2;
303       pt2.x = m_MotionCells.at (i).cell_pt2.x * 2;
304       pt2.y = m_MotionCells.at (i).cell_pt2.y * 2;
305       if (m_useAlpha && m_isVisible) {
306         cvRectangle (transparencyimg,
307             pt1,
308             pt2,
309             CV_RGB (motioncellscolor.B_channel_value,
310                 motioncellscolor.G_channel_value,
311                 motioncellscolor.R_channel_value), CV_FILLED);
312       } else if (m_isVisible) {
313         cvRectangle (p_frame,
314             pt1,
315             pt2,
316             CV_RGB (motioncellscolor.B_channel_value,
317                 motioncellscolor.G_channel_value,
318                 motioncellscolor.R_channel_value), p_thickness);
319       }
320
321     }
322     if (m_useAlpha && m_isVisible) {
323       if (m_MotionCells.size () > 0)
324         blendImages (p_frame, transparencyimg, m_alpha, m_beta);
325     }
326   }
327   return ret;
328 }
329
330 int
331 MotionCells::initDataFile (char *p_datafile, gint64 starttime)  //p_date is increased with difference between current and previous buffer ts
332 {
333   MotionCellData mcd;
334   if (strncmp (p_datafile, " ", 1)) {
335     mc_savefile = fopen (p_datafile, "w");
336     if (mc_savefile == NULL) {
337       //fprintf(stderr, "%s %d:initDataFile:fopen:%d (%s)\n", __FILE__, __LINE__, errno,
338       //strerror(errno));
339       strncpy (m_initdatafilefailed, strerror (errno), BUSMSGLEN - 1);
340       m_initerrorcode = errno;
341       return 1;
342     } else {
343       m_saveInDatafile = true;
344     }
345   } else
346     mc_savefile = NULL;
347
348   //it needs these bytes
349   m_header.itemsize =
350       GINT32_TO_BE ((int) ceil (ceil (m_gridx * m_gridy / 8.0) / 4.0) * 4 +
351       sizeof (mcd.timestamp));
352   m_header.gridx = GINT32_TO_BE (m_gridx);
353   m_header.gridy = GINT32_TO_BE (m_gridy);
354   m_header.starttime = GINT64_TO_BE (starttime);
355
356   snprintf (m_header.name, sizeof (m_header.name), "%s %dx%d", MC_VERSIONTEXT,
357       GINT32_FROM_BE (m_header.gridx), GINT32_FROM_BE (m_header.gridy));
358   m_changed_datafile = false;
359   return 0;
360 }
361
362 int
363 MotionCells::saveMotionCells (gint64 timestamp_millisec)
364 {
365
366   MotionCellData mc_data;
367   mc_data.timestamp = GINT32_TO_BE (timestamp_millisec);
368   mc_data.data = NULL;
369   //There is no datafile
370   if (mc_savefile == NULL)
371     return 0;
372
373   if (ftello (mc_savefile) == 0) {
374     //cerr << "Writing out file header"<< m_header.headersize <<":" << sizeof(MotionCellHeader) << " itemsize:"
375     //<< m_header.itemsize << endl;
376     if (fwrite (&m_header, sizeof (MotionCellHeader), 1, mc_savefile) != 1) {
377       //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
378       //strerror(errno));
379       strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
380       m_saveerrorcode = errno;
381       return -1;
382     }
383   }
384
385   mc_data.data =
386       (char *) calloc (1,
387       GINT32_FROM_BE (m_header.itemsize) - sizeof (mc_data.timestamp));
388   if (mc_data.data == NULL) {
389     //fprintf(stderr, "%s %d:saveMotionCells:calloc:%d (%s)\n", __FILE__, __LINE__, errno,
390     //strerror(errno));
391     strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
392     m_saveerrorcode = errno;
393     return -1;
394   }
395
396   for (unsigned int i = 0; i < m_MotionCells.size (); i++) {
397     int bitnum =
398         m_MotionCells.at (i).lineidx * GINT32_FROM_BE (m_header.gridx) +
399         m_MotionCells.at (i).colidx;
400     int bytenum = (int) floor (bitnum / 8.0);
401     int shift = bitnum - bytenum * 8;
402     mc_data.data[bytenum] = mc_data.data[bytenum] | (1 << shift);
403     //cerr << "Motion Detected " <<  "line:" << m_MotionCells.at(i).lineidx << " col:" << m_MotionCells.at(i).colidx;
404     //cerr << "    bitnum " << bitnum << " bytenum " << bytenum << " shift " << shift << " value " << (int)mc_data.data[bytenum] << endl;
405   }
406
407   if (fwrite (&mc_data.timestamp, sizeof (mc_data.timestamp), 1,
408           mc_savefile) != 1) {
409     //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
410     //strerror(errno));
411     strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
412     m_saveerrorcode = errno;
413     return -1;
414   }
415
416   if (fwrite (mc_data.data,
417           GINT32_FROM_BE (m_header.itemsize) - sizeof (mc_data.timestamp), 1,
418           mc_savefile) != 1) {
419     //fprintf(stderr, "%s %d:saveMotionCells:fwrite:%d (%s)\n", __FILE__, __LINE__, errno,
420     //strerror(errno));
421     strncpy (m_savedatafilefailed, strerror (errno), BUSMSGLEN - 1);
422     m_saveerrorcode = errno;
423     return -1;
424   }
425
426   free (mc_data.data);
427   return 0;
428 }
429
430 double
431 MotionCells::calculateMotionPercentInCell (int p_row, int p_col,
432     double *p_cellarea, double *p_motionarea)
433 {
434   double cntpixelsnum = 0;
435   double cntmotionpixelnum = 0;
436
437   int ybegin = floor ((double) p_row * m_cellheight);
438   int yend = floor ((double) (p_row + 1) * m_cellheight);
439   int xbegin = floor ((double) (p_col) * m_cellwidth);
440   int xend = floor ((double) (p_col + 1) * m_cellwidth);
441   int cellw = xend - xbegin;
442   int cellh = yend - ybegin;
443   int cellarea = cellw * cellh;
444   *p_cellarea = cellarea;
445   int thresholdmotionpixelnum = floor ((double) cellarea * m_sensitivity);
446
447   for (int i = ybegin; i < yend; i++) {
448     for (int j = xbegin; j < xend; j++) {
449       cntpixelsnum++;
450       if ((((uchar *) (m_pbwImage->imageData + m_pbwImage->widthStep * i))[j]) >
451           0) {
452         cntmotionpixelnum++;
453         if (cntmotionpixelnum >= thresholdmotionpixelnum) {     //we dont needs calculate anymore
454           *p_motionarea = cntmotionpixelnum;
455           return (cntmotionpixelnum / cntpixelsnum);
456         }
457       }
458       int remainingpixelsnum = cellarea - cntpixelsnum;
459       if ((cntmotionpixelnum + remainingpixelsnum) < thresholdmotionpixelnum) { //moving pixels number will be less than threshold
460         *p_motionarea = 0;
461         return 0;
462       }
463     }
464   }
465
466   return (cntmotionpixelnum / cntpixelsnum);
467 }
468
469 void
470 MotionCells::calculateMotionPercentInMotionCells (motioncellidx *
471     p_motioncellsidx, int p_motioncells_count)
472 {
473   if (p_motioncells_count == 0) {
474     for (int i = 0; i < m_gridy; i++) {
475       for (int j = 0; j < m_gridx; j++) {
476         m_pCells[i][j].MotionPercent = calculateMotionPercentInCell (i, j,
477             &m_pCells[i][j].CellArea, &m_pCells[i][j].MotionArea);
478         m_pCells[i][j].hasMotion =
479             m_sensitivity < m_pCells[i][j].MotionPercent ? true : false;
480         if (m_pCells[i][j].hasMotion) {
481           MotionCellsIdx mci;
482           mci.lineidx = i;
483           mci.colidx = j;
484           mci.cell_pt1.x = floor ((double) j * m_cellwidth);
485           mci.cell_pt1.y = floor ((double) i * m_cellheight);
486           mci.cell_pt2.x = floor ((double) (j + 1) * m_cellwidth);
487           mci.cell_pt2.y = floor ((double) (i + 1) * m_cellheight);
488           int w = mci.cell_pt2.x - mci.cell_pt1.x;
489           int h = mci.cell_pt2.y - mci.cell_pt1.y;
490           mci.motioncell = cvRect (mci.cell_pt1.x, mci.cell_pt1.y, w, h);
491           m_MotionCells.push_back (mci);
492         }
493       }
494     }
495   } else {
496     for (int k = 0; k < p_motioncells_count; ++k) {
497
498       int i = p_motioncellsidx[k].lineidx;
499       int j = p_motioncellsidx[k].columnidx;
500       m_pCells[i][j].MotionPercent =
501           calculateMotionPercentInCell (i, j,
502           &m_pCells[i][j].CellArea, &m_pCells[i][j].MotionArea);
503       m_pCells[i][j].hasMotion =
504           m_pCells[i][j].MotionPercent > m_sensitivity ? true : false;
505       if (m_pCells[i][j].hasMotion) {
506         MotionCellsIdx mci;
507         mci.lineidx = p_motioncellsidx[k].lineidx;
508         mci.colidx = p_motioncellsidx[k].columnidx;
509         mci.cell_pt1.x = floor ((double) j * m_cellwidth);
510         mci.cell_pt1.y = floor ((double) i * m_cellheight);
511         mci.cell_pt2.x = floor ((double) (j + 1) * m_cellwidth);
512         mci.cell_pt2.y = floor ((double) (i + 1) * m_cellheight);
513         int w = mci.cell_pt2.x - mci.cell_pt1.x;
514         int h = mci.cell_pt2.y - mci.cell_pt1.y;
515         mci.motioncell = cvRect (mci.cell_pt1.x, mci.cell_pt1.y, w, h);
516         m_MotionCells.push_back (mci);
517       }
518     }
519   }
520 }
521
522 void
523 MotionCells::performMotionMaskCoords (motionmaskcoordrect * p_motionmaskcoords,
524     int p_motionmaskcoords_count)
525 {
526   CvPoint upperleft;
527   upperleft.x = 0;
528   upperleft.y = 0;
529   CvPoint lowerright;
530   lowerright.x = 0;
531   lowerright.y = 0;
532   for (int i = 0; i < p_motionmaskcoords_count; i++) {
533     upperleft.x = p_motionmaskcoords[i].upper_left_x;
534     upperleft.y = p_motionmaskcoords[i].upper_left_y;
535     lowerright.x = p_motionmaskcoords[i].lower_right_x;
536     lowerright.y = p_motionmaskcoords[i].lower_right_y;
537     cvRectangle (m_pbwImage, upperleft, lowerright, CV_RGB (0, 0, 0),
538         CV_FILLED);
539   }
540 }
541
542 void
543 MotionCells::performMotionMask (motioncellidx * p_motionmaskcellsidx,
544     int p_motionmaskcells_count)
545 {
546   for (int k = 0; k < p_motionmaskcells_count; k++) {
547     int beginy = p_motionmaskcellsidx[k].lineidx * m_cellheight;
548     int beginx = p_motionmaskcellsidx[k].columnidx * m_cellwidth;
549     int endx =
550         (double) p_motionmaskcellsidx[k].columnidx * m_cellwidth + m_cellwidth;
551     int endy =
552         (double) p_motionmaskcellsidx[k].lineidx * m_cellheight + m_cellheight;
553     for (int i = beginy; i < endy; i++)
554       for (int j = beginx; j < endx; j++) {
555         ((uchar *) (m_pbwImage->imageData + m_pbwImage->widthStep * i))[j] = 0;
556       }
557   }
558 }
559
560 ///BGR if we use only OpenCV
561 //RGB if we use gst+OpenCV
562 void
563 MotionCells::blendImages (IplImage * p_actFrame, IplImage * p_cellsFrame,
564     float p_alpha, float p_beta)
565 {
566
567   int height = p_actFrame->height;
568   int width = p_actFrame->width;
569   int step = p_actFrame->widthStep / sizeof (uchar);
570   int channels = p_actFrame->nChannels;
571   int cellstep = p_cellsFrame->widthStep / sizeof (uchar);
572   uchar *curImageData = (uchar *) p_actFrame->imageData;
573   uchar *cellImageData = (uchar *) p_cellsFrame->imageData;
574
575   for (int i = 0; i < height; i++)
576     for (int j = 0; j < width; j++)
577       for (int k = 0; k < channels; k++)
578         if (cellImageData[i * cellstep + j * channels + k] > 0) {
579           curImageData[i * step + j * channels + k] =
580               round ((double) curImageData[i * step + j * channels +
581                   k] * p_alpha + ((double) cellImageData[i * cellstep +
582                       j * channels + k] * p_beta));
583         }
584 }