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

问题描述 投票:1回答:1

我试图使用python中的机器学习代码获取类别变量的值。虽然当我执行代码时,类别变量根本没有改变,而数据库将类别存储为全局定义的“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机器学习代码返回的,而不是已经定义的类别。

python node.js child-process spawn
1个回答
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");
      }
    });
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.