【问题标题】:Send an image from react to flask and return the ocr value back to react将图像从反应发送到烧瓶并返回 ocr 值以进行反应
【发布时间】:2020-11-25 16:17:09
【问题描述】:

我是 react 新手 .. 我在这里尝试将图像从 react 发送到烧瓶,烧瓶进行 ocr 处理并将结果发送回 react .. 我做了与发送图像相关的部分从对烧瓶做出反应,但我现在被困在从烧瓶发送返回以做出反应的部分......有什么帮助吗?并提前感谢

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

app.js

import React  from 'react';

class Main extends React.Component {
      
    constructor(props) {
    super(props);
    this.state = {
      imageURL: '',
    
    };

    this.handleUploadImage = this.handleUploadImage.bind(this);
    
  }
  
  
  handleUploadImage(ev) {
    ev.preventDefault();

    const data = new FormData();
    data.append('file', this.uploadInput.files[0]);
    data.append('filename', this.fileName.value);
    
    fetch(' http://localhost:5001/ocr ', {
      method: 'POST',
      body: data
    });
  }
    

  render() {
   

      
    return (
      <form onSubmit={this.handleUploadImage}>
        
        <div>
          <input ref={(ref) => { this.uploadInput = ref; }} type="file" />
        </div>
        <div>
          <input ref={(ref) => { this.fileName = ref; }} type="text" placeholder="Enter the desired name of file" />
        </div>
        <br />
        <div>
          <button>Upload</button>
        </div>
        <ul>
        {}
        </ul>
      </form>
    );
  }
}

export default Main;

app.py

import os
import io
import requests
import PIL
from PIL import Image
import tempfile
import urllib.request
import easyocr
from flask import Flask, render_template, request , jsonify, make_response
import shutil
import logging
import json
from urllib.request import urlopen
import numpy as np
import ssl
from flask_cors import CORS , cross_origin


ssl._create_default_https_context = ssl._create_unverified_context


class NumpyEncoder(json.JSONEncoder):
    """ Special json encoder for numpy types """
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

app = Flask(__name__)
CORS(app)
@app.route('/ocr',methods=['POST','GET'])
@cross_origin(origin='*',headers=['Content-Type'])
def ocr():

    print("Recieved Image File")
    file = request.files['file']
    print('File from the POST request is: {}'.format(file))
    img = Image.open(file.stream)
      # img.show()
    img = img.convert("RGB")
    img.save("recogImage.jpg")
    
    reader = easyocr.Reader(['en' , 'ar'])
    bounds = reader.readtext("recogImage.jpg")
    #bounds = reader.readtext(filename)
    
    print('bounds: ',np.array(bounds).tolist())

    response = json.dumps({"bounds": np.array(bounds , dtype=object)}, cls=NumpyEncoder)


    return response

if __name__ == "__main__":
    app.run(port=5001)

【问题讨论】:

    标签: javascript python reactjs flask ocr


    【解决方案1】:

    您的 POST 请求已经返回响应,您只需像这样在 fetch 中处理它:

    import React  from 'react';
    
    class Main extends React.Component {
      
        constructor(props) {
            super(props);
            this.state = {
              imageURL: '',
              ocrData: ''
            };
    
            this.handleUploadImage = this.handleUploadImage.bind(this);
    
        }
    
    
      handleUploadImage(ev) {
          ev.preventDefault();
    
          const data = new FormData();
          data.append('file', this.uploadInput.files[0]);
          data.append('filename', this.fileName.value);
    
          fetch(' http://localhost:5001/ocr ', {
              method: 'POST',
              body: data
          })
          .then((res) => res.json())
          .then((res) => {
              this.setState({
                  ocrData: res.bounds
              }));
      }
    
    
      render() {
          const {ocrData} = this.state;
    
      
          return (
             <form onSubmit={this.handleUploadImage}>
        
             <div>
               <input ref={(ref) => { this.uploadInput = ref; }} type="file" />
             </div>
             <div>
               <input ref={(ref) => { this.fileName = ref; }} type="text" placeholder="Enter the desired name of file" />
             </div>
             <br />
             <div>
               <button>Upload</button>
             </div>
             <ul>
               {}
             </ul>
             <div>{ocrData}</div>
           </form>
    );
    }
      }
    
    export default Main;
    

    【讨论】:

    • 你能告诉我如何在网页中打印退货吗?..告诉我如何编辑我的文件以打印退货
    • 我已经编辑了答案。这应该有效。
    • 它现在向我显示此错误:编译失败。 ./src/App.js 第 37 行:解析错误:意外的令牌,应为“;” 35 | this.setState({ 36 | ocrData: res.bounds > 37 | })); | ^ 38 | 39 | 40 |渲染(){我应该删除“;”还是什么?
    • 不好意思,setState函数后面多了一个括号,请去掉
    • 我删除了它,但仍然有这个错误 第 40 行:解析错误:意外的令牌,预期的“,” 38 | 39 | > 40 |渲染() { | ^ 41 |常量 {ocrData} = this.state; 42 | 43 |返回(
    猜你喜欢
    • 1970-01-01
    • 2020-12-26
    • 2020-04-01
    • 2019-11-14
    • 2019-10-11
    • 1970-01-01
    • 2022-12-13
    • 2017-08-12
    • 1970-01-01
    相关资源
    最近更新 更多