【问题标题】:Reading image file (file storage object) using CV2使用 CV2 读取图像文件(文件存储对象)
【发布时间】:2018-05-10 22:42:27
【问题描述】:

我正在通过 curl 向烧瓶服务器发送图像,我正在使用这个 curl 命令

curl -F "file=@image.jpg" http://localhost:8000/home

我正在尝试在服务器端使用 CV2 读取文件。

在服务器端,我通过此代码处理图像

@app.route('/home', methods=['POST'])
def home():
    data =request.files['file']
    img = cv2.imread(data)
    fact_resp= model.predict(img)
    return jsonify(fact_resp)

我收到了这个错误-

img = cv2.imread(data)
TypeError: expected string or Unicode object, FileStorage found

如何在服务器端使用 CV2 读取文件?

谢谢!

【问题讨论】:

标签: image curl flask cv2


【解决方案1】:

所以如果你想做类似的事情,

file = request.files['file']
img = cv2.imread(file) 

那就这样吧

import numpy as np
file = request.files['file']
npimg = np.fromfile(file, np.uint8)
file = cv2.imdecode(npimg, cv2.IMREAD_COLOR)

现在您不需要再次执行 cv2.imread(),但可以在下一行代码中使用它。

这适用于opencv>3

【讨论】:

    【解决方案2】:

    两行方案,把灰度改成你需要的样子

     npimg = numpy.fromfile(request.files['image'], numpy.uint8)
     # convert numpy array to image
     img = cv2.imdecode(npimg, cv2.IMREAD_GRAYSCALE)
    

    【讨论】:

      【解决方案3】:

      经过一番试验,我自己想出了一种使用 CV2 读取文件的方法。 为此,我首先使用 PIL.image 方法读取图像

      这是我的代码,

      @app.route('/home', methods=['POST'])
      def home():
          data =request.files['file']
          img = Image.open(request.files['file'])
          img = np.array(img)
          img = cv2.resize(img,(224,224))
          img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)
          fact_resp= model.predict(img)
          return jsonify(fact_resp)
      

      我想知道是否有任何直接的方法可以在不使用 PIL 的情况下做到这一点。

      【讨论】:

        【解决方案4】:

        我在使用带有烧瓶服务器的 opencv 时遇到了类似的问题,首先我将图像保存到磁盘并使用保存的文件路径再次使用 cv2.imread()

        读取该图像

        这是一个示例代码:

        data =request.files['file']
        filename = secure_filename(file.filename) # save file 
        filepath = os.path.join(app.config['imgdir'], filename);
        file.save(filepath)
        cv2.imread(filepath)
        

        但现在我通过使用 cv2.imdecode() 从 numpy 数组读取图像,从 here 获得了更有效的方法,如下所示:

        #read image file string data
        filestr = request.files['file'].read()
        #convert string data to numpy array
        npimg = numpy.fromstring(filestr, numpy.uint8)
        # convert numpy array to image
        img = cv2.imdecode(npimg, cv2.CV_LOAD_IMAGE_UNCHANGED)
        

        【讨论】:

        • 对于第二个技巧,使用 img = cv2.imdecode(npimg,cv2.IMREAD_COLOR) for opencv 3.1
        猜你喜欢
        • 2023-03-10
        • 2013-04-01
        • 2023-03-03
        • 2021-11-20
        • 1970-01-01
        • 1970-01-01
        • 2020-04-03
        • 1970-01-01
        • 2010-09-24
        相关资源
        最近更新 更多