Faster RCNN CPU安装记录

本文记录了在没有GPU的情况下安装Faster R-CNN的过程,包括解决cython编译错误、设置CPU_ONLY以及处理下载模型时的超时问题。通过修改setup.py和Makefile.config文件,成功完成了caffe和opencv的配置。尽管在运行demo.py时遇到了matplotlib缺失的错误,但通过安装matplotlib后,最终在CPU模式下成功运行了Faster R-CNN的演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考博客:Faster-RCNN+ZF用自己的数据集训练模型(Python版本)

目前执行了2中的(1)(2),由于在make时遇到了错误(无GPU的原因),搜索了下面的博客进行安装

参考博客:Faster R-CNN算法的Caffe实现

  遇到的问题与相关不同:

1、cython编译出错

python setup.py build_ext --inplace
Traceback (most recent call last):
  File "setup.py", line 56, in <module>
    CUDA = locate_cuda()
  File "setup.py", line 44, in locate_cuda
    raise EnvironmentError('The nvcc binary could not be '
EnvironmentError: The nvcc binary could not be located in your $PATH. Either add it to your path, or set $CUDAHOME
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1
解决方案:

        1)注释掉setup.py中的CUDA = locate_cuda()

      报错:

python setup.py build_ext --inplace
Traceback (most recent call last):
  File "setup.py", line 125, in <module>
    library_dirs=[CUDA['lib64']],
NameError: name 'CUDA' is not defined
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1

      2)寻找setup中所有与gpu有关的代码 注释掉

#    Extension('nms.gpu_nms',
#        ['nms/nms_kernel.cu', 'nms/gpu_nms.pyx'],
#        library_dirs=[CUDA['lib64']],
#        libraries=['cudart'],
#        language='c++',
#        runtime_library_dirs=[CUDA['lib64']],
#        # this syntax is specific to this build system
#        # we're only going to use certain compiler args with nvcc and not with
#        # gcc the implementation of this trick is in customize_compiler() 
### 测量 Faster R-CNN 模型 FPS 的 Python 实现 为了测量 Faster R-CNN 模型的每秒帧数 (Frames Per Second, FPS),可以编写一段简单的 Python 程序,通过计时模型推理时间并计算平均值来得出结果。以下是完整的代码示例以及说明。 #### 代码实现 以下是一个基于 PyTorch 的 Faster R-CNN 推理速度测试脚本: ```python import time import torch from torchvision.models.detection import fasterrcnn_resnet50_fpn from torchvision.transforms import functional as F def load_model(): """加载预训练的 Faster R-CNN 模型""" model = fasterrcnn_resnet50_fpn(pretrained=True) model.eval() # 设置为评估模式 return model def preprocess_image(image_path="test.jpg"): """图像预处理函数""" from PIL import Image image = Image.open(image_path).convert("RGB") # 加载并转换为 RGB 图像 image_tensor = F.to_tensor(image) # 转换为张量 image_tensor = image_tensor.unsqueeze(0) # 添加批次维度 return image_tensor def calculate_fps(model, input_data, num_iterations=100): """计算模型的 FPS""" total_time = 0 with torch.no_grad(): # 关闭梯度计算以加速推断 for _ in range(num_iterations): start_time = time.time() _ = model(input_data) # 进行前向传播 end_time = time.time() inference_time = end_time - start_time total_time += inference_time avg_inference_time = total_time / num_iterations fps = 1 / avg_inference_time return fps, avg_inference_time if __name__ == "__main__": device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 使用 GPU 或 CPU model = load_model().to(device) # 将模型移动到设备上 input_data = preprocess_image().to(device) # 预处理输入数据并移至设备 fps, avg_inference_time = calculate_fps(model, input_data) print(f"Faster R-CNN 平均推理时间为 {avg_inference_time:.4f} 秒.") print(f"Faster R-CNN 的 FPS 为 {fps:.2f}.") ``` --- #### 代码解释 1. **模型加载**: `load_model` 函数负责加载预训练的 Faster R-CNN 模型,并将其设置为评估模式 (`model.eval()`)[^3]。 2. **图像预处理**: `preprocess_image` 函数读取一张图片并将其转换为适合模型输入的形式(即张量)。这里假设有一张名为 `"test.jpg"` 的图片作为输入[^4]。 3. **FPS 计算逻辑**: - 使用 `torch.no_grad()` 上下文管理器关闭梯度计算,从而减少不必要的内存消耗和提高运行效率。 - 对同一张图片重复执行多次推理操作(默认次数为 100),记录每次推理的时间,并最终计算平均值。 - FPS 是指每秒钟能够完成多少次推理,因此可以通过公式 \( \text{FPS} = \frac{1}{\text{Average Inference Time}} \) 来获得[^5]。 4. **设备选择**: 如果有可用的 CUDA 设备,则优先使用 GPU;否则 fallback 到 CPU。 --- #### 注意事项 - 输入图片应具有合理的分辨率,过高的分辨率会显著增加推理时间。 - 可调整 `num_iterations` 参数以获取更精确的 FPS 数据,但需注意过多迭代可能延长总耗时。 - 此方法仅适用于单张图片的推理性能测试,在实际应用中还需考虑批量大小等因素的影响[^6]。 ---
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值