У меня есть файл python, который импортирует функцию из другого файла 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()
Результат вычисляется функцией-single_image_object_counting из python файла object_coutning_api Функция показана ниже:
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, но вывод остается прежним.