Как правильно использовать процессы NodeJS для запуска нескольких процессов обнаружения тензорных потоков? - PullRequest
0 голосов
/ 02 ноября 2019

У меня есть сервер NodeJS, где пользователи могут загрузить изображение для проверки модели обнаружения тензорного потока. Когда второй пользователь загружает изображение, в то время как процесс TF для первого изображения все еще выполняется, первый не создает файл .txt с обнаруженными необходимыми мне координатами. Только второй из них дает правильные результаты

Когда я использовал только один процесс на сервере, каждый второй пользователь помещался в очередь с помощью nodejs. Но тогда время ожидания просто стремительно растет. Поэтому я переместил код, отвечающий за обработку обнаружения изображений, в дочерние процессы nodejs. Затем эти дочерние процессы порождают новый процесс Tensorflow с параметрами для соответствующего пользователя. Процесс обнаружения TF должен затем обнаружить все, что находится на изображении, и вывести координаты всех ограничивающих рамок с высоким показателем в файл .txt. Затем процесс NodeJS возобновляет работу и читает файл .txt для дальнейшей обработки запроса пользователей.

Я перепробовал все методы порождения из NodeJS, но ни один из них не решил эту проблему. Я также изучил многопоточность с помощью TF, но не смог понять, как мне создать начальный сценарий, который затем сообщит процессу, который инстанцировал новое обнаружение, что он завершен.

//The Javascript children process responsible for spawning the TF process

console.log('New file name in child', newFileName, newFilePath);
//call python and wait till the process ended
console.log("Spawning Tensorflow Process...");
var subprocess = childP.execFileSync('python', [
    "-u",
    path.join("C:/tensorflow1/models/research/object_detection/", 'Object_detection_image.py'),
    "-i", newFileName, "-p", newFilePath
]);
console.log("... Tensorflow process finished.");
#the python script used to setup and start TF
import os
import cv2
import numpy as np
import tensorflow as tf
import sys

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")

# Import utilites
from utils import label_map_util
from utils import visualization_utils as vis_util

#input arguments for the script: -i imagename -p fullimagepath

# Name of the directory containing the object detection module we're using
MODEL_NAME = 'inference_graph'
if sys.argv[1] != "-i":
    print("First argument was not '-i', but ", sys.argv[1])
    sys.exit()
IMAGE_NAME = sys.argv[2]
print("ImageName: ", IMAGE_NAME)
# Grab path to current working directory - Edit: Replaced bc the cwd would otherwise be the one of the server
CWD_PATH = "C:/tensorflow1/models/research/object_detection"
print("CurrntWorkingDIrectoy: ", CWD_PATH)
# Path to frozen detection graph .pb file, which contains the model that is used
# for object detection.
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt')

# Path to image
#PATH_TO_IMAGE = os.path.join("E:/Bilder",IMAGE_NAME)
if sys.argv[3] != "-p":
    print("Third argument was not '-p', but ", sys.argv[3])
    sys.exit()
PATH_TO_IMAGE = sys.argv[4]
print("PathToImage", PATH_TO_IMAGE)

# Number of classes the object detector can identify
NUM_CLASSES = 2

# Load the label map.
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

# Load the Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

    sess = tf.Session(graph=detection_graph)

# Define input and output tensors (i.e. data) for the object detection classifier

# Input tensor is the image
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

# Output tensors are the detection boxes, scores, and classes
# 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')

# The 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')

# Number of objects detected
num_detections = detection_graph.get_tensor_by_name('num_detections:0')


# i.e. a single-column array, where each item in the column has the pixel RGB value
image = cv2.imread(PATH_TO_IMAGE)
image_expanded = np.expand_dims(image, axis=0)

# Perform the actual detection by running the model with the image as input
(boxes, scores, classes, num) = sess.run(
    [detection_boxes, detection_scores, detection_classes, num_detections],
    feed_dict={image_tensor: image_expanded})
print("BEFORE")
vis_util.writeCoordinatesIntoFile(
    IMAGE_NAME,
    image,
    np.squeeze(boxes),
    np.squeeze(classes).astype(np.int32),
    np.squeeze(scores),
    category_index,
    use_normalized_coordinates=True,
    line_thickness=7,
    min_score_thresh=0.80)
#the function that should create the .txt file with coordinates 

def writeCoordinatesIntoFile(imageName, p1, p2, p3, p4, p5, use_normalized_coordinates=True,
line_thickness=7,
min_score_thresh=0.80):
    global coordinateList
    lock.acquire()
    path = "pathtofolder/public/ML_Coordinates/" + imageName + ".txt"
    visualize_boxes_and_labels_on_image_array(p1, p2, p3, p4, p5, use_normalized_coordinates=True,
    line_thickness=7,
    min_score_thresh=0.80)

    #append all coordinates to the string written into the file
    fileString = ""
    b = False
    for i in range(0, len(coordinateList)):
        #if (i % 4 ) == 0 and fileString != "":
        #    fileString = fileString + ' '
        fileString = fileString + str(coordinateList[i]) + " "
        b = True
    #write the string into the file
    file = open(path, "w")
    file.write(fileString)
    file.close()

    #clear list for the next call
    coordinateList = []
    lock.release()

Я ожидаю, что при одновременной работе 2+ tf-процессов оба они создают свои файлы .txt. Но на самом деле процесс, который был запущен сначала, не создает файл .txt, а только второй.

Заранее спасибо, Лука

...