hybridgroup / gocv

Go package for computer vision using OpenCV 4 and beyond. Includes support for DNN, CUDA, and OpenCV Contrib.
https://gocv.io
Other
6.62k stars 863 forks source link

VideoCapture up 100 % CPU and memory leak #804

Open Archie1978 opened 3 years ago

Archie1978 commented 3 years ago

Hello, when I use VideoCaptureDevice, I had a 100% CPU and I'd memory leak.

Code:

      cameraCaptureDevice, err := gocv.VideoCaptureDevice(0)
        if err != nil {
                fmt.Fatal("Error device")
        }
        cameraCaptureDevice.Set(gocv.VideoCaptureFrameWidth, 1920)
        cameraCaptureDevice.Set(gocv.VideoCaptureFrameHeight, 1080)
       <- time.After(1000*time.Minute)

My stat after 6 seconde 10542 me 20 0 1468668 57088 24408 S 100.0%CPU 3.0 %RAM 0:06.52 Program_motherb

My stat 2 hour 10542 me 20 0 1534780 157760 24824 S 106.7 %CPU 8.3 %RAM 116:09.85 Program_motherb

Do you have solution for cpu and memory ?

golubaca commented 3 years ago

Yes, use that frames... OpenCV creates buffer for unprocessed frames, and you are just expanding that buffer without using it.

Archie1978 commented 3 years ago

Ah ok, do we know the size of the buffer and stop video acquisition? See even reduce the reduce the size of the acquisition?

Archie1978 commented 3 years ago

So I make this code:

    cameraCaptureDevice, err := gocv.VideoCaptureDevice(0)
    if err != nil {
            return nil, err
    }
    mat := gocv.NewMat()
    cameraCaptureDevice.Set(gocv.VideoCaptureFrameWidth, 1920)
    cameraCaptureDevice.Set(gocv.VideoCaptureFrameHeight, 1080)
    cameraCaptureDevice.Set(gocv.VideoCaptureFPS,1)

    for {
            err:=cameraCaptureDevice.Read(&mat)
            fmt.Println("camera",err)
    }
   <- time.After(1000*time.Minute)

The CPU capture is down to 40% when disabled loop :)

But when I created loop for reading, I had more 1 frame by second and Memory goes up always :(

Archie1978 commented 3 years ago

I tryed this code but I had memory leak:

    stop:=false
    go func(){
            for {
                    if !stop {
                            cameraCaptureDevice.Read(&mat)
                    }else{
                            return
                    }
            }
    }()
    <-time.After(120*time.Minute)
    stop=true
    <-time.After(2*time.Second)
    cameraCaptureDevice.Close()
    <-time.After(999*time.Minute)
deadprogram commented 3 years ago

Sorry, I personally cannot tell what problem might be happening without seeing more of the code.

Most of the time, people's troubles are related to not calling Close() on any Mat that you have created, especially those created inside of a loop. This is why we use the profiler as part of our CI system to try to catch such issues. You can learn more about it and how to apply to testing your own code here: https://github.com/hybridgroup/gocv/blob/release/README.md#profiling