描述这个问题
我已经成功地将我的模型训练在一个自定义数据集上,该数据集有4类大小为480x640的类,使用xception65编码器,使用Deeplab。每当我使用vis.py脚本:克普特,克普特时,我都会在验证集上得到不错的结果。但是,当我冻结模型时,我不会在相同的图像上得到相同的结果。
我使用export_model.py冻结模型,并成功地输出了一个frozen_model.pb文件。然而,当我使用这个pb文件运行推论时,输出总是0(即所有的东西都被归类为“背景”)在我提供的链接到上面的相同的图像上。一切都是黑色的!
我认为这是我如何导出或加载模型的问题,而不一定是模型本身的问题,因为运行vis.py脚本和我的自定义代码进行推理是不同的。也许我没有正确地加载图形或初始化变量。或者我一开始就没有正确地保存体重。任何帮助都将不胜感激!
源代码
下面我提供了我的推理代码:
from deeplab.utils import get_dataset_colormap
from PIL import Image
import tensorflow as tf
import time
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
import glob
# tensorflow arguments
flags = tf.app.flags # flag object for setup
FLAGS = flags.FLAGS # object to access initialized flags
flags.DEFINE_string('frozen', None,
'The path/to/frozen.pb file.')
def _load_graph(frozen):
print('Loading model `deeplabv3_graph` into memory from',frozen)
with tf.gfile.GFile(frozen, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(
graph_def,
input_map=None,
return_elements=None,
name="",
op_dict=None,
producer_op_list=None
)
return graph
def _run_inferences(sess, image, title):
batch_seg_map = sess.run('SemanticPredictions:0',
feed_dict={'ImageTensor:0': [np.asarray(image)]})
semantic_prediction = get_dataset_colormap.label_to_color_image(batch_seg_map[0],
dataset=get_dataset_colormap.__PRDL3_V1).astype(np.uint8)
plt.imshow(semantic_prediction)
plt.axis('off')
plt.title(title)
plt.show()
def main(argv):
# initialize model
frozen = os.path.normpath(FLAGS.frozen)
assert os.path.isfile(frozen)
graph = _load_graph(frozen)
# open graph resource and begin inference in-loop
with tf.Session(graph=graph) as sess:
for img_path in glob.glob('*.png'):
img = Image.open(img_path).convert('RGB')
_run_inferences(sess, img, img_path)
if __name__ == '__main__':
flags.mark_flag_as_required('frozen')
tf.app.run() # call the main() function下面是我使用提供的export_model.py脚本导出模型的代码。
python export_model.py \
--logtostderr \
--atrous_rates=6 \
--atrous_rates=12 \
--atrous_rates=18 \
--output_stride=16 \
--checkpoint_path="/path/to/.../model.ckpt-32245" \
--export_path="/path/to/.../frozen_4_11_19.pb" \
--model_variant="xception_65" \
--num_classes=4 \
--crop_size=481 \
--crop_size=641 \
--inference_scales=1.0系统信息
发布于 2019-12-22 17:05:31
使用以下标志运行导出模型脚本
python deeplab/export_model.py \
--logtostderr \
--model_variant="xception_65" \
--atrous_rates=6 \
--atrous_rates=12 \
--atrous_rates=18 \
--output_stride=16 \
--num_classes=2 \
--decoder_output_stride=4 \
--crop_size=<<crop width>> \
--crop_size=<<crop height>> \
--dataset="shoes" \
--checkpoint_path="<<Checkpoint path>>" \
--export_path="<<Output frozen graph path>>" \发布于 2019-04-18 09:03:29
我也在为我的推论结果而挣扎。但在我的例子中,当使用导出的模型时,我有相当满意的结果,只是它们比我的可视化结果更不准确。
这是我的脚本,它是基于一个可以作为演示的脚本。希望它能帮上忙
import os
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
import time
import cv2
from tqdm import tqdm
import tensorflow as tf
# Needed to show segmentation colormap labels
from deeplab.utils import get_dataset_colormap
from deeplab.utils import labels_alstom
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('model_dir', None, 'Where the model is')
flags.DEFINE_string('image_dir', None, 'Where the image is')
flags.DEFINE_string('save_dir', None, 'Dir for saving results')
flags.DEFINE_string('image_name', None, 'Image name')
class DeepLabModel(object):
"""Class to load deeplab model and run inference."""
INPUT_TENSOR_NAME = 'ImageTensor:0'
OUTPUT_TENSOR_NAME = 'SemanticPredictions:0'
INPUT_SIZE = 513
def __init__(self, model_dir):
"""Creates and loads pretrained deeplab model."""
self.graph = tf.Graph()
graph_def = None
# Extract frozen graph from tar archive.
model_filename = FLAGS.model_dir
with tf.gfile.FastGFile(model_filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
if graph_def is None:
raise RuntimeError('Cannot find inference graph in tar archive.')
with self.graph.as_default():
tf.import_graph_def(graph_def, name='')
self.sess = tf.Session(graph=self.graph)
def run(self, image):
"""Runs inference on a single image.
Args:
image: A PIL.Image object, raw input image.
Returns:
resized_image: RGB image resized from original input image.
seg_map: Segmentation map of `resized_image`.
"""
width, height = image.size
resize_ratio = 1.0 * self.INPUT_SIZE / max(width, height)
target_size = (int(resize_ratio * width), int(resize_ratio * height))
resized_image = image.convert('RGB').resize(target_size, Image.ANTIALIAS)
print('Image resized')
start_time = time.time()
batch_seg_map = self.sess.run(
self.OUTPUT_TENSOR_NAME,
feed_dict={self.INPUT_TENSOR_NAME: [np.asarray(resized_image)]})
print('Image processing finished')
print('Elapsed time : ' + str(time.time() - start_time))
seg_map = batch_seg_map[0]
return resized_image, seg_map
model = DeepLabModel(FLAGS.model_dir)
print('Model created successfully')
def vis_segmentation(image, seg_map):
seg_image = get_dataset_colormap.label_to_color_image(
seg_map, get_dataset_colormap.get_alstom_name()).astype(np.uint8)
return seg_image
def run_demo_image(image_path):
try:
print(image_path)
orignal_im = Image.open(image_path)
except IOError:
print ('Failed to read image from %s.' % image_path)
return
print ('running deeplab on image...')
resized_im, seg_map = model.run(orignal_im)
return vis_segmentation(resized_im, seg_map)
IMAGE_DIR = FLAGS.image_dir
files = os.listdir(FLAGS.image_dir)
for f in tqdm(files):
prediction = run_demo_image(IMAGE_DIR+f)
Image.fromarray(prediction).save(FLAGS.save_dir+'prediction_'+f)
https://stackoverflow.com/questions/55717884
复制相似问题