示例#1
0
        public void FrameIn(object sender, VsImageEventArgs e)
        {
            VsImage img = (VsImage)e.Image.Clone();

            this.vsViewer.SizeMode = PictureBoxSizeMode.StretchImage;

            //if (vsAttachType == VsAttachType.ATTACH_ANALYZER)
            //    this.vsViewer.Image = img.AnalyzedImage;
            //else
            this.vsViewer.Image = img.Image;

            //this.vsViewer.Image.Save("test.bmp");
            // if the first frame -> alert to application and property control
            if (vsStatus == VsViewStatusType.VIEW_CONNECTING)
            {
                // connected flag
                vsStatus = VsViewStatusType.VIEW_CONNECTED;

                // alert to sigleview
                this.vsUpdateEvent(this, new VsMonitorEventArgs(
                                       new VsViewerParas(VsAppControlType.APP_SIGLEVIEW, VsAppControlType.APP_SIGLEVIEW, vsDeviceType, vsDeviceName, VsViewerType.VIEW_STATUS)));

                // alert to application control
                this.vsUpdateEvent(this, new VsMonitorEventArgs(
                                       new VsViewerParas(VsAppControlType.APP_SIGLEVIEW, VsAppControlType.APP_APPICATION, vsDeviceType, vsDeviceName, VsViewerType.VIEW_STATUS)));

                // alert to property control
                this.vsUpdateEvent(this, new VsMonitorEventArgs(
                                       new VsViewerParas(VsAppControlType.APP_SIGLEVIEW, VsAppControlType.APP_PROPERTY, vsDeviceType, vsDeviceName, VsViewerType.VIEW_STATUS)));
            }
        }
示例#2
0
        public VsImage getResultImage()
        {
            lock (this)
            {
                VsImage image = img;

                if (!provicerRuningState)
                {
                    StartProvider();
                }

                while (image == null || image.Image == null)
                {
                    //Monitor.Wait(this);
                    Thread.Sleep(interval);
                    image = img;

                    lock (checkForStopProviderTimer)
                    {
                        lastGetResultImage = 0;
                    }
                }

                lock (checkForStopProviderTimer)
                {
                    lastGetResultImage = 0;
                }

                return(image.Clone());
            }
        }
示例#3
0
        public override void DoRecord(VsImage lastFrame)
        {
            // check if not recording
            if (!bRecord)
            {
                return;
            }
            if (vsEncoder == null)
            {
                bRecord = false; return;
            }

            try
            {
                // record frame
                vsEncoder.DoRecord(lastFrame.Image);
            }
            catch (Exception err)
            {
                // error log
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);

                // dispose encoder
                DisposeEncoder();
            }
        }
示例#4
0
        // Process new frame
        public override void process_Frame1(VsImage lastFrame)
        {
            try
            {
                if (cvAlgo == null)
                {
                    width  = lastFrame.Image.Width;
                    height = lastFrame.Image.Height;
                    cvAlgo = new VsCvMotionHistory(1, 1, width, height, cvDepth.Depth8U, 3);
                    cvAlgo.VsInit();
                    return;
                }

                cvAlgo.VsConfiguration(int.Parse(AnalyzerConfiguration["ThresholdAlpha"].ToString()),
                                       int.Parse(AnalyzerConfiguration["ThresholdSigma"].ToString()));
                lastFrame.Image      = cvAlgo.VsProcess(lastFrame.Image);
                lastFrame.Result     = cvAlgo.VsResult();
                lastFrame.IsAnalyzed = true;
                if (lastFrame.Result.Length > 1)
                {
                    lastFrame.IsDetected = true;
                }
                else
                {
                    lastFrame.IsDetected = false;
                }
            }
            catch { }
        }
示例#5
0
文件: VsPage.cs 项目: tmpkus/openvss
        private void process_NewFrame(object stateInfo)
        {
            Monitor.Enter(lockBuffer);

            try
            {
                Bitmap imgBuffer = GenerateBitmap();
                if (imgBuffer != null)
                {
                    //
                    VsImage lastFrame = new VsImage(imgBuffer);
                    // output
                    if (FrameOut != null)
                    {
                        FrameOut(this, new VsImageEventArgs(lastFrame));
                    }
                }
            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);;
            }
            finally
            {
                Monitor.Exit(lockBuffer);
            }
        }
示例#6
0
 public void StopProvider()
 {
     lock (this)
     {
         coreProvider.Stop();
         coreProvider.WaitForStop();
         img = null;
         provicerRuningState = false;
     }
 }
示例#7
0
        private void process_NewFrame(object stateInfo)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            try
            {
                // get new one
                if (imgBuffer.Count > 0)
                {
                    lastFrame = (VsImage)imgBuffer.Dequeue();
                }

                if (lastFrame != null)
                {
                    using (Graphics gb = Graphics.FromImage(lastFrame.Image))
                    {
                        SolidBrush drawRec = new SolidBrush(Color.Black);
                        gb.FillRectangle(drawRec, 0, 0, lastFrame.Image.Width, 16);
                        //gb.DrawImage(isysLogo, 3, 3, 15, 15);

                        DateTime date = DateTime.Now;

                        // Create font and brush
                        Font       drawFont  = new Font("Tahoma", 10, FontStyle.Bold);
                        SolidBrush drawBrush = new SolidBrush(Color.White);

                        gb.DrawString(date.ToString(), drawFont, drawBrush, new PointF(18, 0));

                        drawBrush.Dispose();
                        drawFont.Dispose();
                        drawRec.Dispose();
                    }

                    // output
                    if (FrameOut != null)
                    {
                        FrameOut(this, new VsImageEventArgs(lastFrame));
                    }
                }
            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);;
            }
            finally
            {
                if (lastFrame != null)
                {
                    lastFrame.Dispose();
                }
                lastFrame = null;
            }
        }
示例#8
0
        // new frame
        protected void OnNewFrame(Bitmap image)
        {
            framesReceived++;
            if (FrameOut != null)
            {
                VsImage img = new VsImage(image);

                FrameOut(this, new VsImageEventArgs(img));

                img.Dispose();
                img = null;
            }
        }
示例#9
0
        // new frame
        protected void OnNewFrame(Bitmap image)
        {
            framesReceived++;
            if ((!stopEvent.WaitOne(0, true)) && (FrameOut != null))
            {
                VsImage img = new VsImage(image);

                // notify client
                FrameOut(this, new VsImageEventArgs(img));
                // release the image
                img.Dispose();
                img = null;
            }
        }
示例#10
0
        private void framedOut(object sender, VsImageEventArgs e)
        {
            //if (BQueue != null)
            //{
            img = (VsImage)e.Image.Clone();
            //Monitor.PulseAll(this);
            //    BQueue.Enqueue(img);
            //}

            //  bmp = img.Image;

            //MessageBox.Show("grameout");
            //((MultimodeVideoSource)coreProvider).FrameOut -= new VsImageEventHandler(framedOut);
            //  coreProvider.Stop();
        }
示例#11
0
        // ---------------------------------------------------------------
        // add image's files to video
        public override void DoRecord(VsImage lastFrame)
        {
            if (vsEncoder != null && vsEncoder.Recording)
            {
                try
                {
                    // record frame
                    vsEncoder.DoRecord(lastFrame.Image);
                }
                catch (Exception err)
                {
                    // error log
                    logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);;

                    // stop encoder
                    StopRecord(false);
                }
            }
        }
示例#12
0
 public override void process_Frame(VsImage lastFrame)
 {
     try
     {
         if (lastFrame.IsDetected)
         {
             StartRecord();
             DoRecord(lastFrame);
         }
         else
         {
             StopRecord();
         }
     }
     catch (Exception err)
     {
         logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);
     }
 }
示例#13
0
        public void FrameIn(object sender, VsImageEventArgs e)
        {
            try
            {
                if (imgBuffer.Count > 1000 / syncTimer)
                {
                    VsImage rm = (VsImage)imgBuffer.Dequeue();
                    rm.Dispose(); rm = null;
                    logger.Log(LogLevel.Warn, DateTime.Now.ToString() + "; frame removed from Streamer");
                }

                VsImage img = (VsImage)e.Image.Clone();
                imgBuffer.Enqueue(img);
            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);
            }
        }
示例#14
0
        // On new frame ready
        //[MethodImpl(MethodImplOptions.Synchronized)]
        public void FrameIn(object sender, VsImageEventArgs e)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            try
            {
                if (imgBuffer.Count >= 1)
                {
                    VsImage rm = (VsImage)imgBuffer.Dequeue();
                    rm.Dispose(); rm = null;
                }

                VsImage img = (VsImage)e.Image.Clone();
                imgBuffer.Enqueue(img);
            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);;
            }
        }
示例#15
0
        public override void DoRecord(VsImage lastFrame)
        {
            if (vsEncoder == null)
            {
                return;
            }

            try
            {
                // record frame
                vsEncoder.DoRecord(lastFrame.Image);
            }
            catch (Exception err)
            {
                // error log
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);

                // if error stop record
                StopRecord();
            }
        }
示例#16
0
        // Process new frame
        public override void process_Frame1(VsImage lastFrame)
        {
            try
            {
                if (cvAlgo == null)
                {
                    width  = lastFrame.Image.Width;
                    height = lastFrame.Image.Height;
                    cvAlgo = new VsCvEllipseDetection(1, 1, width, height, cvDepth.Depth8U, 3);
                    cvAlgo.VsInit();
                    return;
                }

                cvAlgo.VsConfiguration(int.Parse(AnalyzerConfiguration["Threshold"].ToString()));
                lastFrame.Image      = cvAlgo.VsProcess(lastFrame.Image);
                lastFrame.Result     = cvAlgo.VsResult();
                lastFrame.IsAnalyzed = true;
                lastFrame.IsDetected = true;
            }
            catch { }
        }
示例#17
0
        // Input 3
        //[MethodImpl(MethodImplOptions.Synchronized)]
        public void FrameIn3(object sender, VsImageEventArgs e)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            try
            {
                if (imgBuffer3.Count >= bufCount)
                {
                    VsImage rm = (VsImage)imgBuffer3.Dequeue();
                    rm.Dispose(); rm = null;
                    logger.Log(LogLevel.Warn, DateTime.Now.ToString() + "; frame removed from Analyzer");
                }
                VsImage img = (VsImage)e.Image.Clone();
                img.IsDetected = false; img.IsAnalyzed = false;
                imgBuffer3.Enqueue(img);
            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);;
            }
        }
示例#18
0
        private void FrameReceived(object sender, RtpStream.FrameReceivedEventArgs ea)
        {
            try
            {
                if (firstFrame)
                {
                    Bitmap DrawImage = new Bitmap(video_width, video_height);

                    EncoderParameter epQuality = new EncoderParameter(Encoder.Quality, video_quality);
                    // Store the quality parameter in the list of encoder parameters
                    EncoderParameters epParameters = new EncoderParameters(1);
                    epParameters.Param[0] = epQuality;

                    MemoryStream ms = new MemoryStream();
                    DrawImage.Save(ms, GetImageCodecInfo(ImageFormat.Jpeg), epParameters);

                    Array.Copy(ms.GetBuffer(), 0, JpegHeader, 0, offset);
                    firstFrame = false;
                }

                byte[] data = new byte[ea.Frame.Buffer.Length + offset];
                Array.Copy(JpegHeader, data, JpegHeader.Length);
                Array.Copy(ea.Frame.Buffer, 0, data, offset, ea.Frame.Buffer.Length);
                System.IO.MemoryStream msImage = new MemoryStream(data);

                VsImage img   = new VsImage((Bitmap)Image.FromStream(msImage));
                int     index = GetIndex(ea.RtpStream.IPAddress);

                if (index != -1 && vsRtpStream[index] != null && vsRtpStream[index].FrameOut != null)
                {
                    vsRtpStream[index].FrameOut(this, new VsImageEventArgs(img));
                }
                img.Dispose();
                img = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#19
0
        private void process_NewFrame(object stateInfo)
        {
            try
            {
                VsImage lastImage = null;

                // get new one
                if (imgBuffer.Count > 0)
                {
                    lastImage = (VsImage)imgBuffer.Dequeue();
                }

                if (vsReadyToStream && lastImage != null)
                {
                    EncoderParameter epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality);
                    // Store the quality parameter in the list of encoder parameters
                    EncoderParameters epParameters = new EncoderParameters(1);
                    epParameters.Param[0] = epQuality;

                    using (Graphics g = Graphics.FromImage(vsImageStream))
                    {
                        g.DrawImage(lastImage.Image, 0, 0, Width, Height);
                    }

                    MemoryStream ms = new MemoryStream();
                    vsImageStream.Save(ms, GetImageCodecInfo(ImageFormat.Jpeg), epParameters);

                    int offset = search_jpegoffset(ms);
                    data = new byte[(int)ms.Length - offset];
                    Array.Copy(ms.GetBuffer(), offset, data, 0, (int)ms.Length - offset);
                    rtpSender.Send(data);
                }
            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);
            }
        }
示例#20
0
        // ---------------------------------------------------------------
        // Process new frame
        public override void process_Frame(VsImage lastFrame)
        {
            Monitor.Enter(lockEncoder);

            try
            {
                if (lastFrame.IsDetected)
                {
                    width  = lastFrame.Image.Width;
                    height = lastFrame.Image.Height;
                    StartRecord();
                    DoRecord(lastFrame);
                }
                else
                {
                    StopRecord(true);
                }
            }
            finally
            {
                Monitor.Exit(lockEncoder);
            }
        }
示例#21
0
        private void sendStreamMjpegFromProvider(VsProviderManager providerManager, NetworkStream ns, int SendBufferSize, int framRate, Size videoSize, int videoQuality)
        {
            //
            //     BlockingQueue<VsImage> BQueue = new BlockingQueue<VsImage>();

            //    // coreProvider.FrameOut += new VsImageEventHandler(coreProvider_FrameOut);
            //     coreProvider.FrameOut += new VsImageEventHandler (
            //        (object sender, VsImageEventArgs e) =>
            //    {

            //        if (BQueue != null)
            //        {
            //            VsImage img = (VsImage)e.Image.Clone();
            //            BQueue.Enqueue(img);
            //        }

            //    });


            //    coreProvider.Start();
            try
            {
                DateTime start;
                TimeSpan span;

                int frameInterval = 1000 / framRate;

                #region setImageEncoder
                // Get a bitmap.
                // Bitmap bmp1 = new Bitmap(@"c:\TestPhoto.jpg");

                ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

                // Create an Encoder object based on the GUID
                // for the Quality parameter category.
                System.Drawing.Imaging.Encoder myEncoder =
                    System.Drawing.Imaging.Encoder.Quality;

                // Create an EncoderParameters object.
                // An EncoderParameters object has an array of EncoderParameter
                // objects. In this case, there is only one
                // EncoderParameter object in the array.
                EncoderParameters myEncoderParameters = new EncoderParameters();

                // Save the bitmap as a JPG file with zero quality level compression.
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, (long)videoQuality);
                myEncoderParameters.Param[0] = myEncoderParameter;
                #endregion

                MemoryStream stream;
                Bitmap       bmp;
                //double i = 0;
                while (true)
                {
                    stream = new MemoryStream();
                    start  = DateTime.Now;

                    VsImage image = providerManager.getResultImage();

                    bmp = new Bitmap(image.Image, videoSize);

                    //Form1.bmp = new Bitmap(bmp);
                    //bmp.SetResolution(videoSize.Width, videoSize.Height);

                    bmp.Save(stream, jgpEncoder, myEncoderParameters);
                    sendMjpegHead(ns, stream.Length);
                    //bmp.Save(ns, jgpEncoder, myEncoderParameters);
                    //Bitmap.FromStream(stream).Save(ns,ImageFormat.Jpeg);

                    sendStream(ns, SendBufferSize, stream);

                    byte[] bHeadersString = Encoding.ASCII.GetBytes("\r\n");
                    // Send headers
                    ns.Write(bHeadersString, 0, bHeadersString.Length);

                    stream.Close();

                    // ;
                    // i += 1.0 / framRate;
                    //if (i > fe.streamLength)
                    //{
                    //    break;
                    //}


                    span = DateTime.Now.Subtract(start);
                    // miliseconds to sleep
                    int msec = frameInterval - (int)span.TotalMilliseconds;

                    while (msec > 0)
                    {
                        // sleeping ...
                        Thread.Sleep((msec < 100) ? msec : 100);
                        msec -= 100;
                        //span = DateTime.Now.Subtract(start);
                        //msec = frameInterval - (int)span.TotalMilliseconds;
                    }
                }
            }
            finally
            {
                //coreProvider.FrameOut -= new VsImageEventHandler(framedOut);
                //coreProvider.Stop();
            }
        }
        // Process new frame
        public override void process_Frame1(VsImage lastFrame)
        {
            try
            {
                counter++; if (counter > 65000)
                {
                    counter = 0;
                }
                if (threshold2 > 0 && counter % threshold2 != 0)
                {
                    lastFrame.Result     = "";
                    lastFrame.IsAnalyzed = true;
                    lastFrame.IsDetected = bLastDetected;
                    return;
                }

                width  = lastFrame.Image.Width;
                height = lastFrame.Image.Height;

                int fW  = (((width - 1) / block) + 1);
                int fH  = (((height - 1) / block) + 1);
                int len = fW * fH;

                if (bkgFrame == null)
                {
                    threshold1 = double.Parse(AnalyzerConfiguration["ThresholdAlpha"].ToString()) / 100.0;
                    threshold2 = double.Parse(AnalyzerConfiguration["ThresholdSigma"].ToString());

                    // alloc memory for a backgound image and for current image
                    bkgFrame       = new byte[len];
                    curFrame       = new byte[len];
                    dilatatedFrame = new byte[len];

                    // lock image
                    BitmapData imgData = lastFrame.Image.LockBits(
                        new Rectangle(0, 0, width, height),
                        ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                    // create initial backgroung image
                    preprocess_Frame(imgData, width, height, bkgFrame);

                    // unlock the image
                    lastFrame.Image.UnlockBits(imgData);
                }

                // lock image
                BitmapData data = lastFrame.Image.LockBits(
                    new Rectangle(0, 0, width, height),
                    ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                // preprocess input image
                preprocess_Frame(data, width, height, curFrame);

                float alpha = 0.30F;
                for (int i = 0; i < len; i++)
                {
                    bkgFrame[i] = (byte)(alpha * curFrame[i] + (1 - alpha) * bkgFrame[i]);
                }

                // difference and thresholding
                for (int i = 0; i < len; i++)
                {
                    int t = curFrame[i] - bkgFrame[i];
                    if (t < 0)
                    {
                        t = -t;
                    }

                    if (t >= 10)
                    {
                        curFrame[i] = (byte)255;
                    }
                    else
                    {
                        curFrame[i] = (byte)0;
                    }
                }

                // erosion analogue
                // it can be skipped
                pixelsChanged = 0;
                for (int i = 1; i < fH - 1; i++)
                {
                    for (int j = 1; j < fW - 1; j++)
                    {
                        int k = i * fW + j;
                        if (curFrame[k] == 255)
                        {
                            if ((curFrame[i * fW + (j + 1)] == 255) ||
                                (curFrame[i * fW + (j - 1)] == 255) ||
                                (curFrame[(i - 1) * fW + j] == 255) ||
                                (curFrame[(i + 1) * fW + j] == 255))
                            {
                                pixelsChanged += (block * block);
                                curFrame[k]    = (byte)255;
                            }
                            else
                            {
                                curFrame[k] = (byte)0;
                            }
                        }
                    }
                }

                // unlock the image
                lastFrame.Image.UnlockBits(data);

                // postprocess the input image
                // lock image

                /*
                 * lastFrame.AnalyzedImage = (Bitmap)lastFrame.Image.Clone();
                 * BitmapData adata = lastFrame.AnalyzedImage.LockBits(
                 *  new Rectangle(0, 0, width, height),
                 *  ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
                 *
                 * postprocess_Frame(adata, width, height, curFrame);
                 *
                 * lastFrame.AnalyzedImage.UnlockBits(adata);
                 */

                lastFrame.Result     = "";
                lastFrame.IsAnalyzed = true;

                if (CalPixelChange() > threshold1)
                {
                    lastFrame.IsDetected = true;
                    bLastDetected        = true;
                }
                else
                {
                    lastFrame.IsDetected = false;
                    bLastDetected        = false;
                }
            }
            catch { }
        }
示例#23
0
        // Process new frame
        public override void process_Frame1(VsImage lastFrame)
        {
            try
            {
                // frame sampling for background estimation
                // ----------------------------------------------------------------
                counter++; if (counter > 65000)
                {
                    counter = 0;
                }
                if (threshold2 > 0 && counter % threshold2 != 0)
                {
                    lastFrame.Result     = "";
                    lastFrame.IsAnalyzed = true;
                    lastFrame.IsDetected = bLastDetected;
                    return;
                }

                // image scaling
                using (Graphics gp = Graphics.FromImage(curImage)) gp.DrawImage(lastFrame.Image, 0, 0, width, height);

                // first frame checking for memory allocation
                // ----------------------------------------------------------------
                if (bkgFrame == null)
                {
                    threshold1 = double.Parse(AnalyzerConfiguration["ThresholdAlpha"].ToString()) / 100.0;
                    if (threshold1 < 0.1)
                    {
                        threshold1 = 0.005;
                    }
                    threshold2 = double.Parse(AnalyzerConfiguration["ThresholdSigma"].ToString());
                    if (threshold2 < 0)
                    {
                        threshold2 = 1;
                    }

                    // alloc memory for a backgound image and for current image
                    bkgFrame       = new byte[len];
                    curFrame       = new byte[len];
                    dilatatedFrame = new byte[len];

                    // lock image
                    BitmapData imgData = curImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                    // create initial backgroung image
                    preprocess_Frame(imgData, width, height, bkgFrame);

                    // unlock the image
                    curImage.UnlockBits(imgData);
                }

                // background estimation
                // ----------------------------------------------------------------
                // lock image
                BitmapData dataImage = curImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                // preprocess input image
                preprocess_Frame(dataImage, width, height, curFrame);

                // unlock the image
                curImage.UnlockBits(dataImage);

                // update background by running average
                float alpha = 0.30F;
                for (int i = 0; i < len; i++)
                {
                    bkgFrame[i] = (byte)(alpha * curFrame[i] + (1 - alpha) * bkgFrame[i]);
                }

                // motion detection
                // ----------------------------------------------------------------
                // by difference and thresholding
                for (int i = 0; i < len; i++)
                {
                    int t = curFrame[i] - bkgFrame[i];
                    if (t < 0)
                    {
                        t = -t;
                    }

                    if (t >= 5)
                    {
                        curFrame[i] = (byte)255;
                    }
                    else
                    {
                        curFrame[i] = (byte)0;
                    }
                }

                // erosion analogue
                // it can be skipped
                blockChanged = 0;
                for (int i = 1; i < fH - 1; i++)
                {
                    for (int j = 1; j < fW - 1; j++)
                    {
                        int k = i * fW + j;
                        if (curFrame[k] == 255)
                        {
                            if ((curFrame[i * fW + (j + 1)] == 255) ||
                                (curFrame[i * fW + (j - 1)] == 255) ||
                                (curFrame[(i - 1) * fW + j] == 255) ||
                                (curFrame[(i + 1) * fW + j] == 255))
                            {
                                blockChanged += (block * block);
                                curFrame[k]   = (byte)255;
                            }
                            else
                            {
                                curFrame[k] = (byte)0;
                            }
                        }
                    }
                }

                // postprocess the input image
                // lock image

                /*
                 * lastFrame.AnalyzedImage = (Bitmap)curImage.Clone();
                 * BitmapData adata = lastFrame.AnalyzedImage.LockBits(
                 *  new Rectangle(0, 0, width, height),
                 *  ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
                 *
                 * postprocess_Frame(adata, width, height, curFrame);
                 *
                 * lastFrame.AnalyzedImage.UnlockBits(adata);
                 */

                // set motion index
                // ----------------------------------------------------------------
                lastFrame.Result = ""; lastFrame.IsAnalyzed = true;

                double ch = (double)blockChanged / (width * height);
                if (ch > threshold1 && ch < 0.8)
                {
                    lastFrame.IsDetected = true;
                    bLastDetected        = true;
                }
                else
                {
                    lastFrame.IsDetected = false;
                    bLastDetected        = false;
                }
            }
            catch { }
        }
示例#24
0
 // Process new frame
 public override void process_Frame1(VsImage lastFrame)
 {
     lastFrame.Result     = "";
     lastFrame.IsAnalyzed = true;
     lastFrame.IsDetected = true;
 }
示例#25
0
 public virtual void process_Frame5(VsImage lastFrame1, VsImage lastFrame2, VsImage lastFrame3, VsImage lastFrame4, VsImage lastFrame5)
 {
 }
示例#26
0
 public virtual void process_Frame3(VsImage lastFrame1, VsImage lastFrame2, VsImage lastFrame3)
 {
 }
示例#27
0
 public virtual void process_Frame1(VsImage lastFrame1)
 {
 }
示例#28
0
        // Thread entry point
        public void WorkerThread()
        {
            byte[]         buffer = new byte[bufSize];                          // buffer to read stream
            HttpWebRequest req    = null;
            WebResponse    resp   = null;
            Stream         stream = null;
            Random         rnd    = new Random((int)DateTime.Now.Ticks);
            DateTime       start;
            TimeSpan       span;

            while (true)
            {
                int read, total = 0;

                try
                {
                    start = DateTime.Now;

                    // create request
                    if (!preventCaching)
                    {
                        req = (HttpWebRequest)WebRequest.Create(source);
                    }
                    else
                    {
                        req = (HttpWebRequest)WebRequest.Create(source + ((source.IndexOf('?') == -1) ? '?' : '&') + "fake=" + rnd.Next().ToString());
                    }

                    // set login and password
                    if ((login != null) && (password != null) && (login != ""))
                    {
                        req.Credentials = new NetworkCredential(login, password);
                    }
                    // set connection group name
                    if (useSeparateConnectionGroup)
                    {
                        req.ConnectionGroupName = GetHashCode().ToString();
                    }
                    // get response
                    resp = req.GetResponse();

                    // get response stream
                    stream = resp.GetResponseStream();

                    // loop
                    while (!stopEvent.WaitOne(0, true))
                    {
                        // check total read
                        if (total > bufSize - readSize)
                        {
                            total = 0;
                        }

                        // read next portion from stream
                        if ((read = stream.Read(buffer, total, readSize)) == 0)
                        {
                            break;
                        }

                        total += read;

                        // increment received bytes counter
                        bytesReceived += read;
                    }

                    if (!stopEvent.WaitOne(0, true))
                    {
                        // increment frames counter
                        framesReceived++;

                        // image at stop
                        if (FrameOut != null)
                        {
                            Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 0, total));
                            // notify client
                            VsImage img = new VsImage(bmp);
                            FrameOut(this, new VsImageEventArgs(img));
                            // release the image
                            img.Dispose();
                            img = null;
                        }
                    }

                    // wait for a while ?
                    if (frameInterval > 0)
                    {
                        // times span
                        span = DateTime.Now.Subtract(start);
                        // miliseconds to sleep
                        int msec = frameInterval - (int)span.TotalMilliseconds;

                        while ((msec > 0) && (stopEvent.WaitOne(0, true) == false))
                        {
                            // sleeping ...
                            Thread.Sleep((msec < 100) ? msec : 100);
                            msec -= 100;
                        }
                    }
                }
                catch (WebException ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                    // wait for a while before the next try
                    Thread.Sleep(250);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                }
                finally
                {
                    // abort request
                    if (req != null)
                    {
                        req.Abort();
                        req = null;
                    }
                    // close response stream
                    if (stream != null)
                    {
                        stream.Close();
                        stream = null;
                    }
                    // close response
                    if (resp != null)
                    {
                        resp.Close();
                        resp = null;
                    }
                }

                // need to stop ?
                if (stopEvent.WaitOne(0, true))
                {
                    break;
                }
            }
        }
示例#29
0
        private void process_NewFrame(object sender, System.Timers.ElapsedEventArgs e)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            // Stop analyzer
            StopAnalyzer();

            try
            {
                // input frame
                if (numInput >= 5)
                {
                    if (lastFrame5 == null && imgBuffer5.Count > 0)
                    {
                        lastFrame5 = (VsImage)imgBuffer5.Dequeue();
                    }
                    if (lastFrame5 == null)
                    {
                        return;
                    }
                }

                if (numInput >= 4)
                {
                    if (lastFrame4 == null && imgBuffer4.Count > 0)
                    {
                        lastFrame4 = (VsImage)imgBuffer4.Dequeue();
                    }
                    if (lastFrame4 == null)
                    {
                        return;
                    }
                }

                if (numInput >= 3)
                {
                    if (lastFrame3 == null && imgBuffer3.Count > 0)
                    {
                        lastFrame3 = (VsImage)imgBuffer3.Dequeue();
                    }
                    if (lastFrame3 == null)
                    {
                        return;
                    }
                }

                if (numInput >= 2)
                {
                    if (lastFrame2 == null && imgBuffer2.Count > 0)
                    {
                        lastFrame2 = (VsImage)imgBuffer2.Dequeue();
                    }
                    if (lastFrame2 == null)
                    {
                        return;
                    }
                }

                if (numInput >= 1)
                {
                    if (lastFrame1 == null && imgBuffer1.Count > 0)
                    {
                        lastFrame1 = (VsImage)imgBuffer1.Dequeue();
                    }
                    if (lastFrame1 == null)
                    {
                        return;
                    }
                }

                // process
                if (numInput == 5)
                {
                    process_Frame5(lastFrame1, lastFrame2, lastFrame3, lastFrame4, lastFrame5);
                }
                if (numInput == 4)
                {
                    process_Frame4(lastFrame1, lastFrame2, lastFrame3, lastFrame4);
                }
                if (numInput == 3)
                {
                    process_Frame3(lastFrame1, lastFrame2, lastFrame3);
                }
                if (numInput == 2)
                {
                    process_Frame2(lastFrame1, lastFrame2);
                }
                if (numInput == 1)
                {
                    process_Frame1(lastFrame1);
                }

                if (lastFrame1 != null)
                {
                    if (lastFrame1.IsDetected)
                    {
                        if (!lastMotion)
                        {
                            // new motion occurs
                            // alert motion
                            EventAlert();
                        }
                        // still moving
                        timeSave   = interLength;
                        lastMotion = true;
                        lastResult = lastFrame1.Result;
                    }
                    else
                    {
                        if (timeSave > 0)
                        {
                            // motion smoothing
                            lastFrame1.IsDetected = true;
                            lastFrame1.Result     = lastResult;
                            lastMotion            = true;
                        }
                        else
                        {
                            // motion disappear
                            lastMotion = false;
                            lastResult = "";
                        }
                    }

                    // draw image
                    DrawMotion(lastFrame1.Image, lastFrame1.IsDetected);
                }

                // send out
                if (numOutput >= 5)
                {
                    if (FrameOut5 != null)
                    {
                        FrameOut5(this, new VsImageEventArgs(lastFrame5));
                    }
                }
                if (numOutput >= 4)
                {
                    if (FrameOut4 != null)
                    {
                        FrameOut4(this, new VsImageEventArgs(lastFrame4));
                    }
                }
                if (numOutput >= 3)
                {
                    if (FrameOut3 != null)
                    {
                        FrameOut3(this, new VsImageEventArgs(lastFrame3));
                    }
                }
                if (numOutput >= 2)
                {
                    if (FrameOut2 != null)
                    {
                        FrameOut2(this, new VsImageEventArgs(lastFrame2));
                    }
                }
                if (numOutput >= 1)
                {
                    if (FrameOut1 != null)
                    {
                        FrameOut1(this, new VsImageEventArgs(lastFrame1));
                    }
                }
            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);;
            }
            finally
            {
                // free buffer
                if (numInput >= 5 && lastFrame5 != null)
                {
                    lastFrame5.Dispose(); lastFrame5 = null;
                }
                if (numInput >= 4 && lastFrame4 != null)
                {
                    lastFrame4.Dispose(); lastFrame4 = null;
                }
                if (numInput >= 3 && lastFrame3 != null)
                {
                    lastFrame3.Dispose(); lastFrame3 = null;
                }
                if (numInput >= 2 && lastFrame2 != null)
                {
                    lastFrame2.Dispose(); lastFrame2 = null;
                }
                if (numInput >= 1 && lastFrame1 != null)
                {
                    lastFrame1.Dispose(); lastFrame1 = null;
                }

                // Start analyzer
                StartAnalyzer();
            }
        }
示例#30
0
        // Thread entry point
        public void WorkerThread()
        {
            byte[] buffer = new byte[bufSize];  // buffer to read stream

            while (true)
            {
                // reset reload event
                reloadEvent.Reset();

                HttpWebRequest req = null;
                WebResponse    resp = null;
                Stream         stream = null;
                byte[]         delimiter = null;
                byte[]         delimiter2 = null;
                byte[]         boundary = null;
                int            boundaryLen, delimiterLen = 0, delimiter2Len = 0;
                int            read, todo = 0, total = 0, pos = 0, align = 1;
                int            start = 0, stop = 0;

                // align
                //  1 = searching for image start
                //  2 = searching for image end
                try
                {
                    // create request
                    req = (HttpWebRequest)WebRequest.Create(source);
                    // set login and password
                    if ((login != null) && (password != null) && (login != ""))
                    {
                        req.Credentials = new NetworkCredential(login, password);
                    }
                    // set connection group name
                    if (useSeparateConnectionGroup)
                    {
                        req.ConnectionGroupName = GetHashCode().ToString();
                    }
                    // get response
                    resp = req.GetResponse();

                    // check content type
                    string ct = resp.ContentType;
                    if (ct.IndexOf("multipart/x-mixed-replace") == -1)
                    {
                        throw new ApplicationException("Invalid URL");
                    }

                    // get boundary
                    ASCIIEncoding encoding = new ASCIIEncoding();
                    boundary    = encoding.GetBytes(ct.Substring(ct.IndexOf("boundary=", 0) + 9));
                    boundaryLen = boundary.Length;

                    // get response stream
                    stream = resp.GetResponseStream();

                    // loop
                    while ((!stopEvent.WaitOne(0, true)) && (!reloadEvent.WaitOne(0, true)))
                    {
                        // check total read
                        if (total > bufSize - readSize)
                        {
                            total = pos = todo = 0;
                        }

                        // read next portion from stream
                        if ((read = stream.Read(buffer, total, readSize)) == 0)
                        {
                            throw new ApplicationException();
                        }

                        total += read;
                        todo  += read;

                        // increment received bytes counter
                        bytesReceived += read;

                        // does we know the delimiter ?
                        if (delimiter == null)
                        {
                            // find boundary
                            pos = ByteArrayUtils.Find(buffer, boundary, pos, todo);

                            if (pos == -1)
                            {
                                // was not found
                                todo = boundaryLen - 1;
                                pos  = total - todo;
                                continue;
                            }

                            todo = total - pos;

                            if (todo < 2)
                            {
                                continue;
                            }

                            // check new line delimiter type
                            if (buffer[pos + boundaryLen] == 10)
                            {
                                delimiterLen = 2;
                                delimiter    = new byte[2] {
                                    10, 10
                                };
                                delimiter2Len = 1;
                                delimiter2    = new byte[1] {
                                    10
                                };
                            }
                            else
                            {
                                delimiterLen = 4;
                                delimiter    = new byte[4] {
                                    13, 10, 13, 10
                                };
                                delimiter2Len = 2;
                                delimiter2    = new byte[2] {
                                    13, 10
                                };
                            }

                            pos += boundaryLen + delimiter2Len;
                            todo = total - pos;
                        }

                        // search for image
                        if (align == 1)
                        {
                            start = ByteArrayUtils.Find(buffer, delimiter, pos, todo);
                            if (start != -1)
                            {
                                // found delimiter
                                start += delimiterLen;
                                pos    = start;
                                todo   = total - pos;
                                align  = 2;
                            }
                            else
                            {
                                // delimiter not found
                                todo = delimiterLen - 1;
                                pos  = total - todo;
                            }
                        }

                        // search for image end
                        while ((align == 2) && (todo >= boundaryLen))
                        {
                            stop = ByteArrayUtils.Find(buffer, boundary, pos, todo);
                            if (stop != -1)
                            {
                                pos  = stop;
                                todo = total - pos;

                                // increment frames counter
                                framesReceived++;

                                // image at stop
                                if (FrameOut != null)
                                {
                                    Bitmap  bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, start, stop - start));
                                    VsImage img = new VsImage(bmp);

                                    // notify client
                                    FrameOut(this, new VsImageEventArgs(img));
                                    // release the image
                                    img.Dispose();
                                    img = null;
                                }

                                // shift array
                                pos  = stop + boundaryLen;
                                todo = total - pos;
                                Array.Copy(buffer, pos, buffer, 0, todo);

                                total = todo;
                                pos   = 0;
                                align = 1;
                            }
                            else
                            {
                                // delimiter not found
                                todo = boundaryLen - 1;
                                pos  = total - todo;
                            }
                        }
                    }
                }
                catch (WebException ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                    // wait for a while before the next try
                    Thread.Sleep(250);
                }
                catch (ApplicationException ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                    // wait for a while before the next try
                    Thread.Sleep(250);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                }
                finally
                {
                    // abort request
                    if (req != null)
                    {
                        req.Abort();
                        req = null;
                    }
                    // close response stream
                    if (stream != null)
                    {
                        stream.Close();
                        stream = null;
                    }
                    // close response
                    if (resp != null)
                    {
                        resp.Close();
                        resp = null;
                    }
                }

                // need to stop ?
                if (stopEvent.WaitOne(0, true))
                {
                    break;
                }
            }
        }