繁体   English   中英

复制 Python 工作流程以在 Javascript 环境中对 Tensorflow 的图像进行预处理

[英]Replicating a Python workflow for pre-processing of an image for Tensorflow in a Javascript environment

在我的 python 代码中,我正在预处理图像并将其提供给 model 以进行预测。:

path = "/Users/iamreddy831/Desktop/ArchitecturalStyle_ML/FinalTests/testimage3.jpg"
styles = ["Baroque", "NeoClassical", "Gothic", "Modern", "Victorian"]
def read_image(file_path):
    print("[INFO] loading and preprocessing image…") 
    image = load_img(file_path, target_size=(300, 300)) 
    image = img_to_array(image) 
    image = np.expand_dims(image, axis=0)
    image /= 255. 
    return image
def test_single_image(path):
    styles = ["Baroque", "NeoClassical", "Gothic", "Modern", "Victorian"]
    images = read_image(path)
    time.sleep(.5)
    bt_prediction = vgg19.predict(images) 
    tf.shape(bt_prediction)
    preds = model.predict(bt_prediction)
    for idx, styles, x in zip(range(0,7), styles, preds[0]):
        print("ID: {}, Label: {} {}%".format(idx, styles, round(x*100,2) ))
        print("Final Decision:")
    time.sleep(.5)
    for x in range(3):
        print("."*(x+1))
    time.sleep(.2)
    class_predicted = np.argmax(model.predict(bt_prediction), axis=-1)
    class_dictionary = generator_top.class_indices 
    inv_map = {v: k for k, v in class_dictionary.items()} 
    print("ID: {}, Label: {}".format(class_predicted[0],  inv_map[class_predicted[0]])) 
    return load_img(path)

如何在网页上运行此 python 代码以预处理来自页面的图像以供输入? I looked into Tensorflow.js and recreating the workflow, but I think because it relies on applications.vgg19 (which exists in Tensorflow but not Tensorflow.js) I have to create a python environment to do the same/similar thing:

<script type="text/javascript">
async function run(){

  const image = tf.browser.fromPixels(imgcanvas);
  const batchedImage = languagePluginLoader.then(function () {
      console.log(pyodide.runPython(`
          import sys
          sys.version
          import tensorflow as tf
          from tensorflow import keras
          from tensorflow.keras import applications
          tf.keras.applications.vgg19.preprocess_input(
            image, data_format=None
      `));
    });
  const MODEL_URL = 'web_model/model.json';
  const model = await tf.loadGraphModel(MODEL_URL);
  const result = model.predict(batchedImage);
  result.print();
run();
</script>

在这种情况下,我是否正确使用了 Pyodide? 尝试实时执行此操作时,我不断收到语法错误。 或者有没有更简单的方法来解决这个问题? 重塑相当复杂,一个依赖于卷积层的 [-1, 9, 9, 512] 数组。

您的一般方法看起来是正确的(不确定为什么会出现语法错误),但是一个主要限制是您只能导入 带有为 pyodide 构建的 C 扩展的包 Tensorflow 不在列表中,考虑到它相当复杂并且有很长的依赖项列表,它不太可能很快添加。

因此,您将无法在 pyodide 中导入 tensorflow 或 keras。 如果您只需要应用tf.keras.applications.vgg19.preprocess_input ,您可以使用 function 并将其调整为纯 Z2EA9510C37F7F89E4941FF75F62 如果您直接在 CBod1FF75F62 中定义它应该可以工作。

关于语法错误,可能会尝试逐步删除代码行,直到它可以识别问题为止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM