TensorFlow模型变量重用问题
# predict.py
import numpy as np
import tensorflow as tf
from PIL import Image
import time
import fcrn
def predict(model_data_path, image_path , png_path):
# Default input size
height = 228
width = 304
channels = 3
batch_size = 1
# Read image
try:
img = Image.open(image_path)
except:
str1 = '无法打开图像'
str2 = '请检查图像是否完整'
return str1, str2
img_format = img.format
if img_format not in ['jpeg', 'JPEG']:
str1 = '图像不是jpg格式'
str2 = '请重新输入jpg图像'
return str1, str2
img = img.resize([width, height], Image.ANTIALIAS)
img = np.array(img).astype('float32')
img = np.expand_dims(np.asarray(img), axis=0)
# Create a placeholder for the input image
input_node = tf.placeholder(tf.float32, shape=(None, height, width, channels))
# Construct the network
net = fcrn.ResNet50UpProj({'data': input_node}, batch_size, 1, False)
with tf.Session() as sess:
# Load the converted parameters
# print('Loading the model')
# Use to load from ckpt file
time1 = time.time()
saver = tf.train.Saver()
saver.restore(sess, model_data_path)
time2 = time.time()
print('加载模型时间:', time2 - time1)
# Use to load from npy file
#net.load(model_data_path, sess)
# Evalute the network for the given image
pred = sess.run(net.get_output(), feed_dict={input_node: img})
max_depth = pred[0, :, :, 0].max()
min_depth = pred[0, :, :, 0].min()
# print(max_depth, min_depth)
# 深度转灰度
png_array = (pred[0, :, :, 0] - min_depth) / (max_depth - min_depth) * 255.0
# 灰度转深度系数
alpha = (max_depth - min_depth) / 255.0
beta = min_depth
# png_array = pred[0, :, :, 0] / max_depth * 255
depth_png = Image.fromarray(np.uint8(png_array))
depth_png.save(png_path)
return alpha, beta
import predict
model = './ckpt/NYU_FCRN.ckpt'
image_path1 = './test_image/test1.jpg'
png_path1 = './test1.png'
image_path2 = './test_image/test2.jpg'
png_path2 = './test2.png'
image_path3 = './test_image/test3.jpg'
png_path3 = './test3.png'
x, y = predict_new_new.predict(model, image_path1, png_path1)
print(x, y)
print('\n')
x, y = predict_new_new.predict(model, image_path2, png_path2)
print(x, y)
print('\n')
x, y = predict_new_new.predict(model, image_path3, png_path3)
print(x, y)
print('\n')
报错
ValueError: Variable conv1/weights already exists, disallowed.
Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope?
Originally defined at:
解决办法
在with tf.Session() as sess: 下面加一句
tf.get_variable_scope().reuse_variables()就行了