使用CV2读取图像文件(文件存储对象)

Reading image file (file storage object) using CV2

我正在通过 curl 将图像发送到 flask 服务器,我正在使用这个 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 读取文件?

谢谢!

经过一些实验,我自己找到了一种使用 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 的直接方法。

我在将 opencv 与 Flask 服务器一起使用时遇到了类似的问题,因为首先我将图像保存到磁盘并使用 cv2.imread()[=21= 使用保存的文件路径再次读取该图像]

这是一个示例代码:

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)

两行解决,把灰度改成你需要的

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

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

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