【问题标题】:Unable to a function with tensorflow session multiple times无法多次使用 tensorflow 会话的功能
【发布时间】:2020-03-16 12:12:38
【问题描述】:

我有一个 python 文件,它从另一个使用 tensorflow 会话的 python 文件导入函数,如下所示:

counting.py

import requests
import time
import os
import tensorflow as tf

# Object detection imports
from utils import backbone
from api import object_counting_api
def count_object():
    input_video = "img.jpg"
    detection_graph, category_index = backbone.set_model('My_graph', 'detection.pbtxt')
    is_color_recognition_enabled = 0
    tf.reset_default_graph()
    result = object_counting_api.single_image_object_counting(input_video, detection_graph, category_index, is_color_recognition_enabled)
    print(result)
    time.sleep(2.4)

while True:
    count_object()

结果由python文件object_coutning_api中的一个函数-single_image_object_counting计算得出 功能如下图:

import tensorflow as tf
import csv
import cv2
import numpy as np
from utils import visualization_utils as vis_util

def single_image_object_counting(input_video, detection_graph, category_index, is_color_recognition_enabled):     
        counting_mode = "..."
        with detection_graph.as_default():
          with tf.Session(graph=detection_graph) as sess:
            # Definite input and output Tensors for detection_graph
            image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

            # Each box represents a part of the image where a particular object was detected.
            detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

            # Each score represent how level of confidence for each of the objects.
            # Score is shown on the result image, together with the class label.
            detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
            detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
            num_detections = detection_graph.get_tensor_by_name('num_detections:0')            



            input_frame = cv2.imread(input_video)

        # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
            image_np_expanded = np.expand_dims(input_frame, axis=0)

        # Actual detection.
            (boxes, scores, classes, num) = sess.run(
                [detection_boxes, detection_scores, detection_classes, num_detections],
                feed_dict={image_tensor: image_np_expanded})

        # insert information text to video frame
            font = cv2.FONT_HERSHEY_SIMPLEX

        # Visualization of the results of a detection.        
            counter, csv_line, counting_mode = vis_util.visualize_boxes_and_labels_on_single_image_array(1,input_frame,
                                                                                              1,
                                                                                              is_color_recognition_enabled,
                                                                                              np.squeeze(boxes),
                                                                                              np.squeeze(classes).astype(np.int32),
                                                                                              np.squeeze(scores),
                                                                                              category_index,
                                                                                              use_normalized_coordinates=True,
                                                                                              line_thickness=4)
            if(len(counting_mode) == 0):
                cv2.putText(input_frame, "...", (10, 35), font, 0.8, (0,255,255),2,cv2.FONT_HERSHEY_SIMPLEX)                       
            else:
                cv2.putText(input_frame, counting_mode, (10, 35), font, 0.8, (0,255,255),2,cv2.FONT_HERSHEY_SIMPLEX)

            #cv2.imshow('tensorflow_object counting_api',input_frame)        
            cv2.waitKey(0)
            return counting_mode
            sess.close()

计数模式第一次返回计数但再次执行失败。 我正在监视一个不时覆盖其图像的目录。我需要执行一次counting.py文件并更快地获得结果,因为重新启动python文件将需要更多时间,因为它将一次又一次地启动Tensorflow。 如果任何人都可以提供多次运行该功能的解决方案,那将是一个很大的帮助。

这个的输出是:

'defected:': 1, 'perfect:': 1
    (program doesn't end)

我尝试在 single_image_counting 函数结束时关闭会话,但输出保持不变。

【问题讨论】:

  • 解决了这个问题的问题:stackoverflow.com/questions/48767184/…
  • 您能否详细说明究竟是什么解决了您的问题以造福于社区。谢谢!
  • 我已经在下面确切地提到了我是如何解决上述问题的。请参考。 @TensorflowWarriors

标签: python tensorflow deep-learning object-detection


【解决方案1】:

关键是在初始化张量和运行会话时使用 xrange 的 for 循环,并在每次运行时重新初始化所有变量。

  with detection_graph.as_default():
      with tf.Session(graph=detection_graph) as sess:
        tf.initialize_all_variables().run()

        # Definite input and output Tensors for detection_graph
        for time in xrange(1,2):
            image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

        # Each box represents a part of the image where a particular object was detected.
            detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

        # Each score represent how level of confidence for each of the objects.
        # Score is shown on the result image, together with the class label.
            detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
            detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
            num_detections = detection_graph.get_tensor_by_name('num_detections:0')            



            input_frame = cv2.imread(input_video)

    # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
            image_np_expanded = np.expand_dims(input_frame, axis=0)

    # Actual detection.
            for num in xrange(1,3):
                print(num)
                (boxes, scores, classes, num) = sess.run(
                    [detection_boxes, detection_scores, detection_classes, num_detections],
                    feed_dict={image_tensor: image_np_expanded})
                font = cv2.FONT_HERSHEY_SIMPLEX

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多