我有一个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文件,而仅产生第二个文件。
预先感谢, 路卡