deeplab_demo.ipynb转.py文件

outline.py 求区域外包络的测试代码

#!/usr/bin/env python
# coding: utf-8

import os
from io import BytesIO
import tarfile
import tempfile
from six.moves import urllib

from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
import cv2

import tensorflow as tf
os.environ['CUDA_VISIBLE_DEVICES']='1'



class DeepLabModel(object):
  """Class to load deeplab model and run inference."""

  INPUT_TENSOR_NAME = 'ImageTensor:0'
  OUTPUT_TENSOR_NAME = 'SemanticPredictions:0'
  INPUT_SIZE = 1280
  FROZEN_GRAPH_NAME = 'frozen_inference_graph'

  def __init__(self, tarball_path):
    """Creates and loads pretrained deeplab model."""
    self.graph = tf.Graph()

    graph_def = None
    # Extract frozen graph from tar archive.
    tar_file = tarfile.open(tarball_path)
    for tar_info in tar_file.getmembers():
      if self.FROZEN_GRAPH_NAME in os.path.basename(tar_info.name):
        file_handle = tar_file.extractfile(tar_info)
        graph_def = tf.GraphDef.FromString(file_handle.read())
        break

    tar_file.close()

    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):
    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)
    batch_seg_map = self.sess.run(
        self.OUTPUT_TENSOR_NAME,
        feed_dict={self.INPUT_TENSOR_NAME: [np.asarray(resized_image)]})
    seg_map = batch_seg_map[0]
    return resized_image, seg_map

def create_pascal_label_colormap():
  colormap = np.zeros((256, 3), dtype=int)
  ind = np.arange(256, dtype=int)

  for shift in reversed(range(8)):
    for channel in range(3):
      colormap[:, channel] |= ((ind >> channel) & 1) << shift
    ind >>= 3
  return colormap

def label_to_color_image(label):
  if label.ndim != 2:
    raise ValueError('Expect 2-D input label')
  colormap = create_pascal_label_colormap()
  if np.max(label) >= len(colormap):
    raise ValueError('label value too large.')
  return colormap[label]


def outline_compute(segged_image):
  segged_image[segged_image>0]=255
  s_hull=[]
  contours, hierarchy = cv2.findContours(segged_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  for i in range(len(contours)):
    for j in range(len(contours[i])):
        s_hull.append(contours[i][j])
  hull=np.array(s_hull)
  return hull


if __name__ == "__main__":
    LABEL_NAMES = np.asarray([
        'background', 'road_day', 'road_night'  
    ])
    FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)
    FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)

    model_path ='/home/user07/tensorflow/models/research/deeplab/datasets/railway/export/frozen_inference_graph-60000.tar.gz'
    MODEL = DeepLabModel(model_path)
    print('model loaded successfully!')
    image_path = '/home/user07/tensorflow/models/research/deeplab/datasets/railway/image/666.jpg'
    original_im = Image.open(image_path)
    resized_im, seg_map = MODEL.run(original_im)
    seg_map=seg_map.astype(np.uint8)
    hull=outline_compute(seg_map)
    drawing = np.zeros((original_im.size[1], original_im.size[0], 3), np.uint8)
    image_hull=cv2.convexHull(hull,False)
    image_hull = image_hull.reshape((-1,1,2))
    cv2.fillPoly(drawing, [image_hull], (255,255,255))
    cv2.imwrite('result.jpg', drawing)





y

你可能感兴趣的:(AI语义分割,deeplab,deeplab)