通过对caffe已有模型进行finetune 实现医学图像CT肺 结节的预测与检测,并实现可视化!
import os
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#设置caffe源码所在的路径
caffe_root = '/usr/local/caffe/'
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
#加载均值文件
mean_filename='./imagenet_mean.binaryproto'
proto_data = open(mean_filename, "rb").read()
a = caffe.io.caffe_pb2.BlobProto.FromString(proto_data)
mean = caffe.io.blobproto_to_array(a)[0]
#创建网络,并加载已经训练好的模型文件
nodule_net_pretrained='./mytask_train_iter_8000.caffemodel'
nodule_net_model_file='./deploy.prototxt'
nodule_net = caffe.Classifier(nodule_net_model_file, nodule_net_pretrained,
mean=mean,
channel_swap=(2,1,0),#RGB通道与BGR
raw_scale=255,#把图片归一化到0~1之间
image_dims=(256, 256))#设置输入图片的大小
(10, 3, 227, 227)
#预测分类及其可特征视化
nodule_list=['bg','nodule'] #类别表
example_image = './2.bmp'
input_image = caffe.io.load_image(example_image)#读取图片
_ = plt.imshow(input_image)#显示原图片
#预测结果
prediction = nodule_net.predict([input_image])
print 'predict bg or nodule:', nodule_list[prediction[0].argmax()]
predict bg or nodule: bg
#预测分类及其可特征视化
nodule_list=['bg','nodule'] #类别表
example_image = './136.bmp'
input_image = caffe.io.load_image(example_image)#读取图片
_ = plt.imshow(input_image)#显示原图片
#预测结果
prediction = nodule_net.predict([input_image])
print 'predict bg or nodule:', nodule_list[prediction[0].argmax()]
predict bg or nodule: nodule
def showimage(im):
if im.ndim == 3:
im = im[:, :, ::-1]
plt.set_cmap('jet')
plt.imshow(im)
def vis_square(data, padsize=1, padval=0):
data -= data.min()
data /= data.max()
# force the number of filters to be square
n = int(np.ceil(np.sqrt(data.shape[0])))
padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))
# tile the filters into an image
data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
showimage(data)
age_net = caffe.Classifier(nodule_net_model_file, nodule_net_pretrained,
channel_swap=(2,1,0),
raw_scale=255,
image_dims=(256, 256))
prediction = nodule_net.predict([input_image])
_ = plt.imshow(input_image)
filters = nodule_net.params['conv1'][0].data[:49] #conv1滤波器可视化
vis_square(filters.transpose(0, 2, 3, 1))
feat = nodule_net.blobs['conv1'].data[4, :49] #The first Conv layer output, conv1 (rectified responses of the filters above)
vis_square(feat, padval=1)
哇塞,可视化成功~不得不佩服Python的强大