Reading image file (file storage object) using CV2

☆樱花仙子☆ 提交于 2019-12-03 14:45:47

I had similar issues while using opencv with flask server, for that first i saved the image to disk and read that image using saved filepath again using cv2.imread()

Here is a sample code:

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)

But now i have got even more efficient approach from here by using cv2.imdecode() to read image from numpy array as below:

#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)

After a bit of experimentation, I myself figured out a way to read the file using CV2. For this I first read the image using PIL.image method

This is my code,

@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)

I wonder if there is any straight forward way to do this without using PIL.

Two-line solution, change grayscale to what you need

 npimg = numpy.fromfile(request.files['image'], numpy.uint8)
 # convert numpy array to image
 img = cv2.imdecode(npimg, cv2.IMREAD_GRAYSCALE)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!