修改caffe中resize的方式

28 篇文章 5 订阅
13 篇文章 0 订阅

opencv的resize默认的是使用双线性插值INTER_LINEAR,也可以是尝试其他的方式进行插值操作

if (param.random_interpolation_method()) {
    // 0: INTER_NEAREST
    // 1: INTER_LINEAR
    // 2: INTER_CUBIC
    // 3: INTER_AREA
    // 4: INTER_LANCZOS4
    int interpolation = caffe_rng_rand() % 5;
    cv::resize(cv_img_origin, img, cv::Size(new_width, new_height), 0, 0,
        interpolation);
  } else if (param.use_self_resize_fun()) {
    // TODO(kun): resize_model() now is not well verified.
    // When use_self_resize_fun, we consider cv::resize() just in case.
    if (caffe_rng_rand() % 2) {
      cv::resize(cv_img_origin, img, cv::Size(new_width, new_height));
    } else {
      img = cv::Mat(new_height, new_width, cv_img_origin.type());
      int mode = caffe_rng_rand() % 2;
      resize_model(img.data, cv_img_origin.data,
          cv_img_origin.cols, cv_img_origin.rows,
          new_width, new_height, NULL, mode);
    }
  } else {  // Resize using INTER_LINEAR
    cv::resize(cv_img_origin, img, cv::Size(new_width, new_height));
  }

在windows平台上,本地训练SSD_512得到了对应的权值参数文件,加载模型进行前向测试的时候,发现调用caffe.io.Transformer中的resize处理函数速度太慢,打算用opencv的resize做替换,因此更改了输入图片到模型中的预处理过程,使用caffe.io.Transformer进行预处理的过程如下:

import numpy as np
import sys,os
# 设置当前的工作环境在caffe下
caffe_root = '/home/xxx/caffe/'
# 我们也把caffe/python也添加到当前环境
sys.path.insert(0, caffe_root + 'python')
import caffe
os.chdir(caffe_root)#更换工作目录
 
# 设置网络结构
net_file=caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt'
# 添加训练之后的参数
caffe_model=caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'
# 均值文件
mean_file=caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy'
 
# 这里对任何一个程序都是通用的,就是处理图片
# 把上面添加的两个变量都作为参数构造一个Net
net = caffe.Net(net_file,caffe_model,caffe.TEST)
# 得到data的形状,这里的图片是默认matplotlib底层加载的
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
# matplotlib加载的image是像素[0-1],图片的数据格式[weight,high,channels],RGB
# caffe加载的图片需要的是[0-255]像素,数据格式[channels,weight,high],BGR,那么就需要转换
 
# channel 放到前面
transformer.set_transpose('data', (2,0,1))
transformer.set_mean('data', np.load(mean_file).mean(1).mean(1))
# 图片像素放大到[0-255]
transformer.set_raw_scale('data', 255)
# RGB-->BGR 转换
transformer.set_channel_swap('data', (2,1,0))
 
# 这里才是加载图片
im=caffe.io.load_image(caffe_root+'examples/images/cat.jpg')
# 用上面的transformer.preprocess来处理刚刚加载图片
net.blobs['data'].data[...] = transformer.preprocess('data',im)
#注意,网络开始向前传播啦
out = net.forward()
# 最终的结果: 当前这个图片的属于哪个物体的概率(列表表示)
output_prob = output['prob'][0]
# 找出最大的那个概率
print 'predicted class is:', output_prob.argmax()

用opencv2中的resize函数替换之后,检测的结果很差,最终通过比较两种resize方式对同一张图片处理后结果的差异,发现两种方式存在不同,虽然说差异很小,但是也会严重影响检测结果,原因可能如下:

模型不够鲁棒
caffe中的resize和opencv中的resize的默认插值方式可能不同,这点需要看源码进行确认

在ubuntu上不存在这个问题,猜想可能是在windows下的caffe不是官方提供的,可能处理方式存在差异
最终,全部采用caffe.io.Transformer的方式进行图片的预处理,检测结果恢复正常。

此外,测试了opencv2和opencv3,发现用opencv2处理图片,检测的效果更好,原因未知!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是基于MobileNet_SSD和Caffe预训练模型检测图像的对象的示例代码: ```python import cv2 import numpy as np # 加载网络模型 net = cv2.dnn.readNetFromCaffe('MobileNetSSD_deploy.prototxt', 'MobileNetSSD_deploy.caffemodel') # 定义类别标签 classNames = { 0: 'background', 1: 'aeroplane', 2: 'bicycle', 3: 'bird', 4: 'boat', 5: 'bottle', 6: 'bus', 7: 'car', 8: 'cat', 9: 'chair', 10: 'cow', 11: 'diningtable', 12: 'dog', 13: 'horse', 14: 'motorbike', 15: 'person', 16: 'pottedplant', 17: 'sheep', 18: 'sofa', 19: 'train', 20: 'tvmonitor' } # 加载图像 image = cv2.imread('image.jpg') # 对图像进行预处理 blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5) # 将预处理后的图像输入到网络,得到预测结果 net.setInput(blob) detections = net.forward() # 遍历预测结果,绘制检测框 for i in range(detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence > 0.5: classId = int(detections[0, 0, i, 1]) className = classNames[classId] x1 = int(detections[0, 0, i, 3] * image.shape[1]) y1 = int(detections[0, 0, i, 4] * image.shape[0]) x2 = int(detections[0, 0, i, 5] * image.shape[1]) y2 = int(detections[0, 0, i, 6] * image.shape[0]) cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.putText(image, className, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) # 显示检测结果 cv2.imshow('image', image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 需要注意的是,代码的`MobileNetSSD_deploy.prototxt`和`MobileNetSSD_deploy.caffemodel`是MobileNet_SSD的预训练模型文件,需要根据实际情况进行替换。同时,预训练模型定义的类别标签也需要根据实际情况进行修改

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值