首页 > 解决方案 > python 代码中的完整内存使用情况,带有 mediapipe 库

问题描述

我在 python 代码中遇到了一个大问题,我的代码工作正常,但我的笔记本电脑的 RAM 无法擦除未使用的数据,我使用了 'gc' 库,但它没有任何帮助,这个问题似乎是我将其更改为类模式。

我的代码:

import cv2 as cv
import mediapipe as mp
import time
import gc

class handDetector():
    def __init__(self, mode=False, maxHands=2, detectionCon=0.5, trackCon=0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon
        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands, 1, self.detectionCon, self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils
    def findHands(self, image, draw=True):
        imgRGB = cv.cvtColor(image, cv.COLOR_BGR2RGB)
        self.result = self.hands.process(imgRGB)

        if self.result.multi_hand_landmarks:
            for hand in self.result.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(image, hand, self.mpHands.HAND_CONNECTIONS)
                     cv.FILLED)
        return image
    def findPosition(self, image, handNo=0, draw=True):
        lmList = []
        h, w, c = image.shape
        if self.result.multi_hand_landmarks:
            myHand = self.result.multi_hand_landmarks[handNo]
            for id, land in enumerate(myHand.landmark):
                cx, cy = int(land.x * w), int(land.y * h)
                lmList.append([id, cx, cy])
                if draw:
                    cv.circle(image, (cx,cy), 15, (0,0,255), cv.FILLED)
        return lmList


def main():
    cap = cv.VideoCapture(0)
    ret=1   
    pre_time = time.time()
    gc.enable()
    while ret:
        ret, frame = cap.read()
        crt_time = time.time()
        fps = int(1/(crt_time-pre_time))
        handDtc = handDetector()
        image = handDtc.findHands(frame)
        lmList = handDtc.findPosition(image) 
        cv.putText(image, str(fps), (50,50), cv.FONT_HERSHEY_COMPLEX, 1, (255,255,0))        
        image=frame
        cv.imshow('image', image)
        pre_time = time.time()     
        if cv.waitKey(1) == ord('q'):
            ret = False
            # print(lmList)
        del handDtc
        del image
        gc.collect()
if __name__ == "__main__":
    main()

 

我的 RAM 存储空间是 16gb,我有 11gb 空闲空间,运行代码后我的 RAM 将满

标签: pythonpython-3.xopencvrammediapipe

解决方案


我必须将handDtc = handDetector()里面的时间移到外面。这条线产生了许多类对象,它会填满我的 RAM。


推荐阅读