python - 我无法在全局范围内从 process.stdout.on 获取数据

标签 python node.js child-process spawn

我正在尝试使用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()

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

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

最佳答案

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");
      }
    });
  });
}

关于python - 我无法在全局范围内从 process.stdout.on 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55781665/

相关文章:

python线程: only one Python thread is running

node.js - 使用 exec() 创建 child_process 时从子进程向父进程发送消息

node.js - 带有正斜杠的窗口中的Nodejs绝对路径

Electron app.relaunch() 松散标准输入输出

node.js - ChildProcess 是运行还是死亡? - Node .js

python - 最近是否有一个带有简单 "assert"的 pytest 替代方案?

当使用 Hook 到某些应用程序时,pythoncom 在 KeyDown 上崩溃

node.js - 在ubuntu 18.04中安装npm时出错

node.js - 如何从 child_process stdout 检索对象?

用于测量电池时间的python脚本