Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我无法从process.stdout.on全局获取数据_Python_Node.js_Child Process_Spawn - Fatal编程技术网

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

Python 我无法从process.stdout.on全局获取数据,python,node.js,child-process,spawn,Python,Node.js,Child Process,Spawn,我试图使用python中的机器学习代码获取category变量的值。虽然当我执行代码时,category变量根本没有改变,数据库将category存储为“A”,它是在全局外部定义的。据我所知,这是由于一些异步行为,但我不知道实际的解决方案 var category = "A"; if (type == "lost") { var spawn = require("child_process").spawn; var process = spawn('python', ["./evalua

我试图使用python中的机器学习代码获取category变量的值。虽然当我执行代码时,category变量根本没有改变,数据库将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()
导入系统 从keras导入后端为K 导入初始版本4 将numpy作为np导入 进口cv2 导入操作系统 导入argparse image=sys.argv[1] #如果要使用GPU,请在此处设置其索引 os.environ['CUDA_VISIBLE_DEVICES']=' #此函数来自Google的ImageNet预处理脚本 def中央_裁剪(图像,中央_部分): 如果中心分数为1.0: raise VALUE ERROR('中心分数必须在(0,1)之内') 如果中心_分数==1.0: 返回图像 img_shape=image.shape 深度=img_形状[2] 分数偏移=int(1/((1-中心分数)/2.0)) bbox\u h\u start=int(np.除法(img\u形状[0],分数\u偏移)) bbox_w_start=int(np.除法(img_形状[1],分数偏移)) bbox\u h\u size=int(img\u形状[0]-bbox\u h\u开始*2) bbox_w_size=int(img_形状[1]-bbox_w_开始*2) image=image[bbox_h_开始:bbox_h_开始+bbox_h_大小,bbox_w_开始:bbox_w_开始+bbox_大小] 返回图像 def get_processed_图像(img_路径): #加载图像并从BGR转换为RGB im=np.asarray(cv2.imread(img_路径))[:,:,::-1] im=中央作物(im,0.875) im=cv2。调整大小(im,(299299)) im=初始值4。预处理输入(im) 如果K.image_data_format()=“channels_first”: im=np.转置(im,(2,0,1)) im=im.重塑(-1,329999) 其他: im=im.重塑(-1299299,3) 返回即时消息 如果名称=“\uuuuu main\uuuuuuuu”: #创建模型并加载预先训练的权重 model=inception\u v4.创建模型(weights='imagenet',include\u top=True) #打开类标签字典。(给定ID的人类可读标签) classes=eval(打开('validation\u utils/class\u names.txt','r').read()) #负载测试图像! img_path=“../public/files/lost/”+image img=获得经过处理的图像(img\u路径) #测试图像的运行预测 preds=模型预测(img) 打印(“类为:”+classes[np.argmax(preds)-1]) 打印(“确定性为:+str(preds[0][np.argmax(preds)])) sys.stdout.flush() 这是一个目录结构,用于计算通过HTML表单输入的watch.jpg上的python脚本


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

事件处理程序异步运行,您不必等待所有输出被使用

使用该事件检测输出的结束,并运行将新的
丢失的
对象保存在那里的代码

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

数据
事件处理程序异步运行,您不必等待所有输出都被使用

使用该事件检测输出的结束,并运行将新的
丢失的
对象保存在那里的代码

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

process.stdout.on()
函数异步运行。问题仍然没有解决。
process.stdout.on()
函数异步运行。问题仍然没有解决。我尝试了与您建议的相同方法,但它仍然将类别保存为“A”。请尝试将
console.log
添加到
data
处理程序中,以查看是否从python进程中获取数据。我不确定原因,但console.log也不会输出任何内容。请尝试使用
process.on(“error”,…)检查错误
我已使用python脚本和目录结构编辑了问题。脚本运行良好,问题或多或少与文件的正确路径有关。我无法识别相同的问题,需要帮助。感谢帮助。我尝试使用与您建议的相同方法,但仍将类别保存为“A”。尝试将
console.log
添加到
data
处理程序中,以查看是否从python进程中获取数据。我不确定原因,但console.log也不输出任何内容。尝试使用
process.on(“error”,…)检查错误
我已经用python脚本和目录结构编辑了这个问题。脚本运行良好,问题或多或少与文件的正确路径有关。我无法识别相同的问题,需要帮助。感谢帮助。