我无法从全球的process.stdout.on获取数据

时间:2019-04-21 09:50:23

标签: python node.js child-process spawn

我正在尝试使用python中的机器学习代码来获取category变量的值。虽然当我执行代码时类别变量根本没有改变,并且数据库将类别存储为“ A”,这是在全局外部定义的。据我所知,这是由于某些异步行为引起的,但我不知道实际的解决方案。

var category = "A";
if (type == "lost") {
  var spawn = require("child_process").spawn;
  var process = spawn('python', ["./evaluate_lost.py", req.body.image]);
  process.stdout.on('data', function(data) {
    category += data.toString();
  });
  var newLost = {
    name: name,
    date: date,
    time: time,
    location: location,
    phone: phone,
    image: image,
    description: desc,
    category: category,
    author: author
  };
  // Create a new lost and save to DB
  Lost.create(newLost, function(err, newlyCreated) {
    if (err) {
      console.log(err);
    } else {
      //redirect back to items page
      res.redirect("/items");
    }
  });
}

好吧,我正在使用Evaluate_lost.py脚本和目录结构来编辑问题。

import sys
from keras import backend as K
import inception_v4
import numpy as np
import cv2
import os
import argparse

image=sys.argv[1]


# If you want to use a GPU set its index here
os.environ['CUDA_VISIBLE_DEVICES'] = ''


# This function comes from Google's ImageNet Preprocessing Script
def central_crop(image, central_fraction):
    if central_fraction <= 0.0 or central_fraction > 1.0:
        raise ValueError('central_fraction must be within (0, 1]')
    if central_fraction == 1.0:
        return image

    img_shape = image.shape
    depth = img_shape[2]
    fraction_offset = int(1 / ((1 - central_fraction) / 2.0))
    bbox_h_start = int(np.divide(img_shape[0], fraction_offset))
    bbox_w_start = int(np.divide(img_shape[1], fraction_offset))

    bbox_h_size = int(img_shape[0] - bbox_h_start * 2)
    bbox_w_size = int(img_shape[1] - bbox_w_start * 2)

    image = image[bbox_h_start:bbox_h_start+bbox_h_size, bbox_w_start:bbox_w_start+bbox_w_size]
    return image


def get_processed_image(img_path):
    # Load image and convert from BGR to RGB
    im = np.asarray(cv2.imread(img_path))[:,:,::-1]
    im = central_crop(im, 0.875)
    im = cv2.resize(im, (299, 299))
    im = inception_v4.preprocess_input(im)
    if K.image_data_format() == "channels_first":
        im = np.transpose(im, (2,0,1))
        im = im.reshape(-1,3,299,299)
    else:
        im = im.reshape(-1,299,299,3)
    return im


if __name__ == "__main__":
    # Create model and load pre-trained weights
    model = inception_v4.create_model(weights='imagenet', include_top=True)

    # Open Class labels dictionary. (human readable label given ID)
    classes = eval(open('validation_utils/class_names.txt', 'r').read())

    # Load test image!
    img_path = "../public/files/lost/" + image
    img = get_processed_image(img_path)

    # Run prediction on test image
    preds = model.predict(img)
    print("Class is: " + classes[np.argmax(preds)-1])
    print("Certainty is: " + str(preds[0][np.argmax(preds)]))
    sys.stdout.flush()

这是评估watch.jpg上的python脚本的目录结构,该脚本通过HTML表单输入

我希望类别是从python机器学习代码返回的,而不是已经定义的类别。

1 个答案:

答案 0 :(得分:0)

data事件处理程序异步运行,您不必等待所有输出都被消耗。

使用end事件检测输出的结尾,然后运行将新的Lost对象保存在其中的代码。

var category = "A";
if (type == "lost") {
  var spawn = require("child_process").spawn;
  var process = spawn('python', ["./evaluate_lost.py", req.body.image]);
  process.stdout.on('data', function(data) {
    category += data.toString();
  });
  process.stdout.on('end', function() {
    var newLost = {
      name: name,
      date: date,
      time: time,
      location: location,
      phone: phone,
      image: image,
      description: desc,
      category: category,
      author: author
    };
    // Create a new lost and save to DB
    Lost.create(newLost, function(err, newlyCreated) {
      if (err) {
        console.log(err);
      } else {
        //redirect back to items page
        res.redirect("/items");
      }
    });
  });
}