caffe中的模型测试之灰度图测试设置

【0、参考资料】

https://blog.csdn.net/weixin_40695510/article/details/81281442

【1、读入图像并转化为灰度图】

img=caffe.io.load_image(img_path, color=False) 
  • 此句读入图像并转化为单通道灰度图,值为float型,范围是0~1.0
  • 举个例子,自己写的,还望纠错:
#coding=utf-8
import os
import sys
import numpy as np 
import cv2

caffe_root = '/your/caffe/address/' # /home/myname/caffe/
filepath = '/my/file/address/'
sys.path.insert(0, caffe_root+'python') #优先import insert的地址
import caffe 

caffe.set_mode_gpu() # 设置GPU模式
os.chdir(caffe_root) # 用于改变当前工作目录到指定的路径。

deploy = filepath + 'test_net/ResNet18_deploy.prototxt' #加载网络
caffe_model = filepath + 'model/ResNet18/_iter_10500.caffemodel' #加载训练好的模型

dir = filepath + 'selected_test/' #测试数据集

filelist = []
labels = [] 
with open(filepath + 'Test.txt','r') as f:
    for line in f:
        a = line.split(' ')[0]
        b = line.split(' ')[1][0]
        filelist.append(a)
        labels.append(b)

net = caffe.Net(deploy, caffe_model, caffe.TEST)

#preprocess
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2, 0, 1))
transformer.set_raw_scale('data', 255)

total = len(filelist)
right = 0.0
accuracy = 0.0 

for i in range(total):
    img = filelist[i
    im = caffe.io.load_image(dir+img, color = False) #color = False确定了读出来的图片是灰度图
    net.blobs['data'].data[...]=transformer.preprocess('data',im)
    out = net.forward()
    output_prob = out['prob'][0]
    if int(output_prob.argmax()) == int(labels[i]):
        right += 1

if right != 0:
    accuracy = right/total

print("this accuracy is {}".format(accuracy))

你可能感兴趣的:(caffe中的模型测试之灰度图测试设置)