使用前要用下面的命令加载一个库,并且下载vgg16.npy,另外不建议直接使用代码,还是自己用老师给的,再慢慢查错比较好。
最后还是有一个报错,不影响结果,暂时没时间修复。
考试的时候出现了:已放弃(核心已转储),重新开了终端,用网上的sudo解决发现库不能全部加载,然后直接不加sudo运行就没有错误提示了。
虚拟机的linux好慢,加到3G内存也好慢。
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple scikit-image
Nclass.py
略
utils.py
#!/usr/bin/python
#coding:utf-8
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from pylab import mpl
mpl.rcParams['font.sans-serif']=['SimHei'] # 正常显示中文标签
mpl.rcParams['axes.unicode_minus']=False # 正常显示正负号
def load_image(path):
fig = plt.figure("Centre and Resize")
img = io.imread(path)
img = img / 255.0
ax0 = fig.add_subplot(131)
ax0.set_xlabel(u'Original Picture')
ax0.imshow(img)
short_edge = min(img.shape[:2])
y = (img.shape[0] - short_edge) // 2
x = (img.shape[1] - short_edge) // 2
crop_img = img[y:y+short_edge, x:x+short_edge]
ax1 = fig.add_subplot(132)
ax1.set_xlabel(u"Centre Picture")
ax1.imshow(crop_img)
re_img = transform.resize(crop_img, (224, 224))
ax2 = fig.add_subplot(133)
ax2.set_xlabel(u"Resize Picture")
ax2.imshow(re_img)
img_ready = re_img.reshape((1, 224, 224, 3))
return img_ready
def percent(value):
return '%.2f%%' % (value * 100)
vgg16.py
#!/usr/bin/python
#coding:utf-8
import inspect
import os
import numpy as np
import tensorflow as tf
import time
import matplotlib.pyplot as plt
VGG_MEAN = [103.939, 116.779, 123.68]
class Vgg16():
def __init__(self, vgg16_path=None):
if vgg16_path is None:
vgg16_path = os.path.join(os.getcwd(), "vgg16.npy")
self.data_dict = np.load(vgg16_path, encoding='latin1', allow_pickle=True).item()
def forward(self, images):
print("build model started")
start_time = time.time()
rgb_scaled = images * 255.0
red, green, blue = tf.split(rgb_scaled,3,3)
bgr = tf.concat([
blue - VGG_MEAN[0],
green - VGG_MEAN[1],
red - VGG_MEAN[2]],3)
self.conv1_1 = self.conv_layer(bgr, "conv1_1")
self.conv1_2 = self.conv_layer(self.conv1_1, "conv1_2")
self.pool1 = self.max_pool_2x2(self.conv1_2, "pool1")
self.conv2_1 = self.conv_layer(self.pool1, "conv2_1")
self.conv2_2 = self.conv_layer(self.conv2_1, "conv2_2")
self.pool2 = self.max_pool_2x2(self.conv2_2, "pool2")
self.conv3_1 = self.conv_layer(self.pool2, "conv3_1")
self.conv3_2 = self.conv_layer(self.conv3_1, "conv3_2")
self.conv3_3 = self.conv_layer(self.conv3_2, "conv3_3")
self.pool3 = self.max_pool_2x2(self.conv3_3, "pool3")
self.conv4_1 = self.conv_layer(self.pool3, "conv4_1")
self.conv4_2 = self.conv_layer(self.conv4_1, "conv4_2")
self.conv4_3 = self.conv_layer(self.conv4_2, "conv4_3")
self.pool4 = self.max_pool_2x2(self.conv4_3, "pool4")
self.conv5_1 = self.conv_layer(self.pool4, "conv5_1")
self.conv5_2 = self.conv_layer(self.conv5_1, "conv5_2")
self.conv5_3 = self.conv_layer(self.conv5_2, "conv5_3")
self.pool5 = self.max_pool_2x2(self.conv5_3, "pool5")
self.fc6 = self.fc_layer(self.pool5, "fc6")
self.relu6 = tf.nn.relu(self.fc6)
self.fc7 = self.fc_layer(self.relu6, "fc7")
self.relu7 = tf.nn.relu(self.fc7)
self.fc8 = self.fc_layer(self.relu7, "fc8")
self.prob = tf.nn.softmax(self.fc8, name="prob")
end_time = time.time()
print(("time consuming: %f" % (end_time-start_time)))
self.data_dict = None
def conv_layer(self, x, name):
with tf.variable_scope(name):
w = self.get_conv_filter(name)
conv = tf.nn.conv2d(x, w, [1, 1, 1, 1], padding='SAME')
conv_biases = self.get_bias(name)
result = tf.nn.relu(tf.nn.bias_add(conv, conv_biases))
return result
def get_conv_filter(self, name):
return tf.constant(self.data_dict[name][0], name="filter")
def get_bias(self, name):
return tf.constant(self.data_dict[name][1], name="biases")
def max_pool_2x2(self, x, name):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def fc_layer(self, x, name):
with tf.variable_scope(name):
shape = x.get_shape().as_list()
dim = 1
for i in shape[1:]:
dim *= i
x = tf.reshape(x, [-1, dim])
w = self.get_fc_weight(name)
b = self.get_bias(name)
result = tf.nn.bias_add(tf.matmul(x, w), b)
return result
def get_fc_weight(self, name):
return tf.constant(self.data_dict[name][0], name="weights")
app.py
#coding:utf-8
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import vgg16
import utils
from Nclasses import labels
img_path = input('Input the path and image name:')
img_ready = utils.load_image(img_path)
fig=plt.figure(u"Top-5 预测结果")
with tf.Session() as sess:
images = tf.placeholder(tf.float32, [1, 224, 224, 3])
vgg = vgg16.Vgg16()
vgg.forward(images)
probability = sess.run(vgg.prob, feed_dict={images:img_ready})
top5 = np.argsort(probability[0])[-1:-6:-1]
print("top5:",top5)
values = []
bar_label = []
for n, i in enumerate(top5):
print("n:",n)
print("i:",i)
values.append(probability[0][i])
bar_label.append(labels[i])
print(i, ":", labels[i], "----", utils.percent(probability[0][i]))
ax = fig.add_subplot(111)
ax.bar(range(len(values)), values, tick_label=bar_label, width=0.5, fc='g')
ax.set_ylabel(u'probabilityit')
ax.set_title(u'Top-5')
for a,b in zip(range(len(values)), values):
ax.text(a, b+0.0005, utils.percent(b), ha='center', va = 'bottom', fontsize=7)
plt.show()