网上流传的几乎都是这种代码
def see():
# cap = cv2.VideoCapture(path)
cap = cv2.VideoCapture(0)
mpHands = mp.solutions.hands
hands = mpHands.Hands(static_image_mode=False,
max_num_hands=2,
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
mpDraw = mp.solutions.drawing_utils
img = np.zeros((500, 500, 3), np.uint8)
# 浅灰色背景
img.fill(200)
i = 0
while True:
ret, frame = cap.read()
if not ret:
print("读取帧失败!")
break
# frame = cv2.imread('img.png')
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 因为摄像头是镜像的,所以将摄像头水平翻转
# 不是镜像的可以不翻转
# frame = cv2.flip(frame, M_17912)
results = hands.process(frame)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# if results.multi_handedness:
# for hand_label in results.multi_handedness:
# print(type(hand_label))
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
# print('hand_landmarks:',hand_landmarks)
# print("n")
# m = hand_landmarks.landmark
# for id, lm in enumerate(m):
# print("x = {}, y = {}, z = {}".format(lm.x, lm.y, lm.z))
# 关键点可视化
mpDraw.draw_landmarks(
frame, hand_landmarks, mpHands.HAND_CONNECTIONS,
mpDraw.DrawingSpec(color=(255, 255, 255), thickness=0, circle_radius=0),
mpDraw.DrawingSpec(thickness=1, circle_radius=1))
cv2.imshow('MediaPipe Hands', frame)
i = i + 1
if cv2.waitKey(1) & 0xFF == 27:
break
print(cap.get(7), i)
cap.release()
但是,批量运行,内存会越来越大,根本原因还是内存没有释放。实际上,hands这个对象和openCV里cap类似的,都是需要释放的。因此,在程序运行最后要加上hands.close()
改正代码如下:
def see():
# cap = cv2.VideoCapture(path)
cap = cv2.VideoCapture(0)
mpHands = mp.solutions.hands
hands = mpHands.Hands(static_image_mode=False,
max_num_hands=2,
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
mpDraw = mp.solutions.drawing_utils
img = np.zeros((500, 500, 3), np.uint8)
# 浅灰色背景
img.fill(200)
i = 0
while True:
ret, frame = cap.read()
if not ret:
print("读取帧失败!")
break
# frame = cv2.imread('img.png')
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 因为摄像头是镜像的,所以将摄像头水平翻转
# 不是镜像的可以不翻转
# frame = cv2.flip(frame, M_17912)
results = hands.process(frame)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# if results.multi_handedness:
# for hand_label in results.multi_handedness:
# print(type(hand_label))
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
# print('hand_landmarks:',hand_landmarks)
# print("n")
# m = hand_landmarks.landmark
# for id, lm in enumerate(m):
# print("x = {}, y = {}, z = {}".format(lm.x, lm.y, lm.z))
# 关键点可视化
mpDraw.draw_landmarks(
frame, hand_landmarks, mpHands.HAND_CONNECTIONS,
mpDraw.DrawingSpec(color=(255, 255, 255), thickness=0, circle_radius=0),
mpDraw.DrawingSpec(thickness=1, circle_radius=1))
cv2.imshow('MediaPipe Hands', frame)
i = i + 1
if cv2.waitKey(1) & 0xFF == 27:
break
print(cap.get(7), i)
hands.close()
cap.release()



