После того, как я использую эту функцию, я получаю выходные данные размером около 13 ГБ, но моя используемая память составляет 29 ГБ. После анализа памяти я вижу, что память кучи и анон-память занимают много памяти. Я подозреваю, что CV2 распределяет память в куче, потому что , в первый раз, когда я использую эту функцию, она заняла около 27 ГБ, но во второй раз потребовалось меньше, она увеличилась только до 29 ГБ, я использовал gc и пытался удалить переменные, но ничего не помогло, я думаю, что malloc происходит за пределами области видимости, поэтому Python не может ничего сделать, я не знаю, что делать, чтобы очистить эту память, чтобы я мог выполнить следующую фазу процесса, не исчерпав память
import sys
import gc
import cv2
def log_system_memory(stage):
"""Log system memory usage."""
process = psutil.Process()
print(f"[{stage}] Memory usage: {process.memory_info().rss / 1024 ** 2:.2f} MB")
def video_to_test(video_path, text_url, resolution=(224, 224), max_attempts=20, snapshot_file="memory_tracking.txt"):
metadata = parse_text_file(text_url)
end_frame = metadata['video_length']
end_frame -= 2
for attempt in range(max_attempts):
try:
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise ValueError(f"Unable to open video: {video_path}")
frames = []
frame_count = 0
while cap.isOpened() and frame_count < end_frame:
log_system_memory(f"{frame_count} before cap.read")
ret, frame = cap.read()
log_system_memory(f"{frame_count} after cap.read")
# Resize frame
frame_resized = cv2.resize(frame, resolution, interpolation=cv2.INTER_LINEAR)
# Convert BGR to RGB
frame_rgb = cv2.cvtColor(frame_resized, cv2.COLOR_BGR2RGB)
# Normalize frame
frame_normalized = (frame_rgb / 255.0 - np.array([0.485, 0.456, 0.406])) / np.array([0.229, 0.224, 0.225])
# Convert to tensor format: [C, H, W]
frame_preprocessed = torch.tensor(frame_normalized, dtype=torch.float32).permute(2, 0, 1)
frames.append(frame_preprocessed)
frame_count += 1
# Clean up intermediate variables to release memory
# del frame, frame_resized, frame_rgb, frame_normalized, frame_preprocessed
# Run garbage collection periodically (every 100 frames)
if frame_count % 500 == 0:
gc.collect()
log_system_memory(f"{frame_count} frames, after cleanup")
cap.release()
del cap
# Final garbage collection after loop
gc.collect()
log_system_memory("After releasing video capture and cleaning")
if len(frames) == 0:
print(f"No frames extracted on attempt {attempt + 1}. Retrying...")
continue
# Stack frames into a tensor: [num_frames, C, H, W]
video_tensor = torch.stack(frames)
return video_tensor, metadata
except Exception as e:
print(f"Error on attempt {attempt + 1}: {str(e)}, frame: {frame_count}")
if attempt == max_attempts - 1:
raise ValueError(f"Failed to load video after {max_attempts} attempts: {video_path}")
# Return an empty tensor on failure
return torch.empty((0, 3, *resolution), dtype=torch.float32)
Подробнее здесь: https://stackoverflow.com/questions/792 ... opencv-cv2
Как освободить память, выделенную opencv CV2 ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как я могу освободить память, выделенную внешними вызовами C в Python?
Anonymous » » в форуме Python - 0 Ответы
- 22 Просмотры
-
Последнее сообщение Anonymous
-