1

从过去的两周开始,我已经因这个错误而筋疲力尽。我尝试了很多来找出并以不同的方式尝试了代码,但还没有成功。我认为主要问题是位图,可能是我没有以正确的方式使用。我正在分享我的代码以帮助了解我在做什么。

首先我告诉你场景。在这个应用程序中,我使用单反相机进行实时取景。相机类的主要代码区域如下:

internal void Run()
{
    LVrunning = true;
    while (LVrunning)
    {
        Thread.Sleep(20);
        if (LVrunning)
            UpdatePicture();
    }
}

private void UpdatePicture()
{
    try
    {
        if (err == EDSDK.EDS_ERR_OK && LVrunning)
        {
            inSide = true;

            // Download live view image data
            err = EDSDK.EdsDownloadEvfImage(cameraDev, EvfImageRef);

            if (err != EDSDK.EDS_ERR_OK)
            {
                Debug.WriteLine(String.Format("Download of Evf Image: {0:X}", err));
                return;
            }
            IntPtr ipData;
            err = EDSDK.EdsGetPointer(MemStreamRef, out ipData);
            if (err != EDSDK.EDS_ERR_OK)
            {
                Debug.WriteLine(String.Format("EdsGetPointer failed: {0:X}", err));
                return;
            }

            uint len;
            err = EDSDK.EdsGetLength(MemStreamRef, out len);
            if (err != EDSDK.EDS_ERR_OK)
            {
                Debug.WriteLine(String.Format("EdsGetLength failed:{0:X}", err));
                EDSDK.EdsRelease(ipData);
                return;
            }

            Byte[] data = new byte[len];
            Marshal.Copy(ipData, data, 0, (int)len);
            System.IO.MemoryStream memStream = new System.IO.MemoryStream(data);

            // get the bitmap
            Bitmap bitmap = null;
            try
            {
                bitmap = new Bitmap(memStream);
            }
            catch (OutOfMemoryException ex)
            {
                GC.WaitForPendingFinalizers();
                bitmap = new Bitmap(memStream); // sometimes error occur
            }

            NewFrame(bitmap, null); // this is event call back to form area.

            memStream.Dispose();
            EDSDK.EdsRelease(ipData);
        }
    }
    catch (Exception ex)
    {

    }
}
private void getCapturedItem(IntPtr directoryItem)
{
    uint err = EDSDK.EDS_ERR_OK;
    IntPtr stream = IntPtr.Zero;

    EDSDK.EdsDirectoryItemInfo dirItemInfo;

    err = EDSDK.EdsGetDirectoryItemInfo(directoryItem, out dirItemInfo);

    if (err != EDSDK.EDS_ERR_OK)
    {
        throw new CameraException("Unable to get captured item info!", err);
    }

    //  Fill the stream with the resulting image
    if (err == EDSDK.EDS_ERR_OK)
    {
        err = EDSDK.EdsCreateMemoryStream((uint)dirItemInfo.Size, out stream);
    }

    //  Copy the stream to a byte[] and
    if (err == EDSDK.EDS_ERR_OK)
    {
        err = EDSDK.EdsDownload(directoryItem, (uint)dirItemInfo.Size, stream);
    }

    //  Create the returned item
    //CapturedItem item = new CapturedItem();
    if (dirItemInfo.szFileName.ToString().ToLower().Contains("jpg") || dirItemInfo.szFileName.ToString().ToLower().Contains("jpeg"))
    {
        if (err == EDSDK.EDS_ERR_OK)
        {
            IntPtr imageRef = IntPtr.Zero;

            err = EDSDK.EdsCreateImageRef(stream, out imageRef);

            if (err == EDSDK.EDS_ERR_OK)
            {
                EDSDK.EdsImageInfo info;
                err = EDSDK.EdsGetImageInfo(imageRef, EDSDK.EdsImageSource.FullView, out info);
            }
        }
    }

    if (err == EDSDK.EDS_ERR_OK)
    {
        try
        {
            byte[] buffer = new byte[(int)dirItemInfo.Size];
            GCHandle gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            IntPtr address = gcHandle.AddrOfPinnedObject();
            IntPtr streamPtr = IntPtr.Zero;
            err = EDSDK.EdsGetPointer(stream, out streamPtr);
            if (err != EDSDK.EDS_ERR_OK)
            {
                throw new CameraDownloadException("Unable to get resultant image.", err);
            }

            try
            {
                Marshal.Copy(streamPtr, buffer, 0, (int)dirItemInfo.Size);//sometimes error comes here
                System.IO.MemoryStream memStream = new System.IO.MemoryStream(buffer);

                    Bitmap bitmap = null;
                    try
                    {
                        bitmap = new Bitmap(memStream);
                    }
                    catch (OutOfMemoryException ex)
                    {
                        GC.WaitForPendingFinalizers();
                        Bitmap b = new Bitmap(memStream);//sometimes error comes here
                    }

                    if (bitmap != null)
                    {


                            PhotoCaptured(bitmap, null);

                    }

            }
            catch (AccessViolationException ave)
            {
                throw new CameraDownloadException("Error copying unmanaged stream to managed byte[].", ave);
            }
            finally
            {
                gcHandle.Free();
                EDSDK.EdsRelease(stream);
                EDSDK.EdsRelease(streamPtr);
            }
        }
        catch (OutOfMemoryException ex)
        {
            GC.WaitForPendingFinalizers();
            IboothmeObject.minimizeMemory();
            getCapturedItem(directoryItem);
        }
    }
    else
    {
        throw new CameraDownloadException("Unable to get resultant image.", err);
    }
}

在表格方面,图片只是在图片框中更新

private void StartLiveView()
    {
        if (this.liveView.Connected)
        {
            this.liveView.PhotoCaptured += new EventHandler(liveView_PhotoCaptured);
            this.liveView.NewFrame += new EventHandler(liveView_NewFrame);
            this.liveView.StartLiveView();

        }
    }

    void liveView_NewFrame(object sender, EventArgs e)
    {
        this.picMain.Image = sender as Image;
    }
    void liveView_PhotoCaptured(object sender, EventArgs e)
    {
        Image img = sender as Image;
        // this image is big in size like 5000x3000.
        Bitmap tempbitmap = new Bitmap(img.Width, img.Height);// now mostly error comes here
        tempbitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
            using (Graphics g = Graphics.FromImage(tempbitmap))
            {
                g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
                g.Save();
            }
        picMain.Image = tempbitmap;
        tempbitmap.Save(path,ImageFormat.Jpeg);
    }

另一个使用位图和来自相机的实时视图的代码区域。此代码从相机获取框架并在框架上写入一些对象..就我而言,我正在框架上写一些气球

void liveView_NewFrame(object sender, EventArgs e)
    {
        using (Image<Bgr, byte> Frame = new Image<Bgr, byte>(new Bitmap(sender as Image)))
        {
            Frame._SmoothGaussian(3);
            IntPtr hsvImage = CvInvoke.cvCreateImage(CvInvoke.cvGetSize(Frame), Emgu.CV.CvEnum.IPL_DEPTH.IPL_DEPTH_8U, 3);
            CvInvoke.cvCvtColor(Frame, hsvImage, Emgu.CV.CvEnum.COLOR_CONVERSION.CV_BGR2HSV);

            Image<Gray, byte> imgThresh = new Image<Gray, byte>(Frame.Size);
            imgThresh.Ptr = GetThresholdedImage(hsvImage);
            //CvInvoke.cvSmooth(imgThresh, imgThresh, Emgu.CV.CvEnum.SMOOTH_TYPE.CV_GAUSSIAN, 3, 3, 3, 3);

            #region Draw the contours of difference
            //this is tasken from the ShapeDetection Example
            Rectangle largest = new Rectangle();
            try
            {
                using (MemStorage storage = new MemStorage()) //allocate storage for contour approximation
                    //detect the contours and loop through each of them
                    for (Contour<Point> contours = imgThresh.Convert<Gray, Byte>().FindContours(
                          Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
                          Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_EXTERNAL,
                          storage);
                       contours != null;
                       contours = contours.HNext)
                    {
                        //Create a contour for the current variable for us to work with
                        Contour<Point> currentContour = contours.ApproxPoly(contours.Perimeter * 0.05, storage);

                        //Draw the detected contour on the image
                        if (currentContour.Area > ContourThresh) //only consider contours with area greater than 100 as default then take from form control
                        {
                            if (currentContour.BoundingRectangle.Width > largest.Width && currentContour.BoundingRectangle.Height > largest.Height)
                            {
                                largest = currentContour.BoundingRectangle;
                            }
                        }
                        //storage.Dispose();
                    }

            }
            catch (Exception)
            {

            }

            #endregion

            #region Draw Object
            Random r = new Random();
            //Bitmap bb = Frame.Bitmap;
            foreach (var item in objectList)
            {
                using (Graphics g = Graphics.FromImage(Frame.Bitmap))
                {
                    if (DrawAble(item, largest))
                    {
                        if (item.Y < 0)
                        {
                            if (item.X < picMain.Width)
                            {
                                g.DrawImage(item.image, new Rectangle(item.X, 0, item.image.Width, item.image.Height + item.Y),
                                    new Rectangle(), GraphicsUnit.Pixel);
                                item.X += r.Next(-5, 5);
                                item.Y += 15;
                            }
                        }
                        else
                        {
                            if (item.X < picMain.Width && item.Y < picMain.Height)
                            {
                                g.DrawImage(item.image, new Rectangle(item.X, item.Y, item.image.Width, item.image.Height));
                                item.X += r.Next(-5, 5);
                                item.Y += 15;
                            }
                            else
                            {
                                item.X = r.Next(0, picMain.Width - 5);
                                item.Y = r.Next(-item.image.Height, -5);
                            }

                        }
                    }
                    else
                    {
                        item.X = r.Next(0, picMain.Width - 5);
                        item.Y = r.Next(-item.image.Height, -5);
                    }

                }
            }

            #endregion

            picMain.Image = Frame.ToBitmap();

        }

        minimizeMemory();
    }

现在我详细分享整个问题。首先,我为实时视图创建了一个表单,并通过使用 opencv(Emgu) 库,我在框架上绘制气球。在实时视图中,这些气球正在移动。另一种形式是从高分辨率的相机中捕获图片。我注意到,我的应用程序内存随着每一帧而增加,并且在捕获 2 张实时视图和 2 张图片后,它会达到 1+ GB。如果我尝试再次显示第一个表单以进行实时视图,则 UpdatePicture() 函数中发生错误。然后我添加代码以最小化当前应用程序的内存。现在我在实时视图中的每一帧之后调用这个函数。在这个解决方案之后,当我检查应用程序的内存时,它不会超过 100mb 或 200mb。但是问题仍然存在。经过几次捕获,从流(bitmap = new Bitmap(memStream);) 获取位图时 UpdatePicture() 发生错误。错误与内存不足相同。经过一番搜索,我找到了这个解决方案。

// get the bitmap
        Bitmap bitmap = null;
        try
        {
            bitmap = new Bitmap(memStream);
        }
        catch (OutOfMemoryException ex)
        {
            GC.WaitForPendingFinalizers();
            bitmap = new Bitmap(memStream);
        }

但不工作错误仍然相同。

错误有时出现在 UpdatePicture() 方法中,有时出现在 liveView_NewFrame 方法中。表示问题与位图、位图大小或内存损坏有关。所以请帮助我。我很担心,两周过去了,但我无法解决这个问题。

4

1 回答 1

3

您正在调用CvInvoke.cvCreateImage创建的数据位于本机堆上
,因此它不会被 GC 收集。
你必须打电话cvReleaseImage(IntPtr)来发布数据

有很多内存分析器可以帮助理解问题

尝试使用ANTS Memory Profiler 7

于 2013-07-10T07:22:21.840 回答