第3章 环境搭建
OpenCV · NumPy · Matplotlib · PyTorch / TensorFlow 安装与配置 · GPU 加速检查
工欲善其事,必先利其器。本章将引导你完成从基础科学计算库到深度学习框架的完整安装,并验证 GPU 加速环境是否就绪。所有操作均基于 Python 3.9+ 与 pip/conda 包管理器。
3.1 基础库安装
使用 pip 一次性安装核心依赖:
pip install numpy matplotlib opencv-python opencv-contrib-python
验证安装:
import numpy as np
import cv2
import matplotlib.pyplot as plt
print(f"NumPy version: {np.__version__}")
print(f"OpenCV version: {cv2.__version__}")
💡 提示: 推荐使用虚拟环境(venv 或 conda)隔离项目依赖,避免版本冲突。
3.2 深度学习框架安装
根据你的硬件与需求选择 PyTorch 或 TensorFlow(可同时安装)。
| 框架 | 安装命令 (CPU) | 安装命令 (GPU / CUDA 12.x) |
|---|---|---|
| PyTorch | pip install torch torchvision torchaudio | pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 |
| TensorFlow | pip install tensorflow | pip install tensorflow[and-cuda] |
安装后快速验证框架是否可导入:
# PyTorch
import torch
print(f"PyTorch version: {torch.__version__}")
# TensorFlow
import tensorflow as tf
print(f"TensorFlow version: {tf.__version__}")
3.3 GPU 加速环境检查
确保 CUDA 工具包与深度学习框架的 GPU 后端正常工作。
PyTorch GPU 检查
import torch
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"GPU count: {torch.cuda.device_count()}")
print(f"GPU name: {torch.cuda.get_device_name(0)}")
TensorFlow GPU 检查
import tensorflow as tf
print(f"GPU devices: {tf.config.list_physical_devices('GPU')}")
⚠️ 常见问题: 若 GPU 不可用,请检查驱动版本(
nvidia-smi)、CUDA 版本匹配以及 cuDNN 安装。Windows 用户注意 Visual Studio 运行时组件。
3.4 完整环境验证脚本
将以下代码保存为 check_env.py 并运行,一键输出所有关键信息:
import sys, numpy as np, cv2, matplotlib, torch, tensorflow as tf
print("="*50)
print("实时图像增强 · 环境检查报告")
print("="*50)
print(f"Python : {sys.version}")
print(f"NumPy : {np.__version__}")
print(f"OpenCV : {cv2.__version__}")
print(f"Matplotlib : {matplotlib.__version__}")
print(f"PyTorch : {torch.__version__}")
print(f"TensorFlow : {tf.__version__}")
print(f"CUDA avail : {torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"GPU name : {torch.cuda.get_device_name(0)}")
print(f"TF GPU list : {tf.config.list_physical_devices('GPU')}")
print("="*50)