deeplabv3+模型训练好后,可以用来预测自己的图片。训练模型过程可以看我前面的文章。
1.预测单张图片
预测本地图片
首先将图片保存好,然后可以参照deeplabv3+官方的demo:deeplab_demo.ipynp编写自己的程序。这里就不放代码了,直接看预测多张图片的。
预测在线图片
需要给定图片的url,也直接看下面的吧。
2.预测多张图片
import os
from io import BytesIO
from six.moves import urllib
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
import tensorflow as tf
import datetime
class DeeplabModel(object):
"""class to load deeplab model and run inference."""
INPUT_TENSOR_NAME = 'ImageTensor:0'
OUTPUT_TENSOR_NAME = 'SemanticPredictions:0'
INPUT_SIZE = 513
FROZEN_GRAPH_NAME = 'frozen_inference_graph'
def __init__(self, model_path):
"""creates and loads pretrained deeplab model."""
self.graph = tf.Graph()
# Extract frozen graph
with open(model_path + "frozen_inference_graph.pb", "rb") as f:
graph_def = tf.GraphDef.FromString(f.read())
if graph_def is None:
raise RuntimeError('cannot find inference graph')
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
"""
width, height = image.size
resize_ratio = 1.0 * self.INPUT_SIZE / max