Python Flask/OpenCV: How do I Cache an arbitrary (OpenCV) object between requests?

ぃ、小莉子 提交于 2019-12-20 06:17:12

问题


In the following snippet I have the usual Flask app calling a function from another python module (also below).

I would like a (slow/expensive/arbitrary) function to be cached in memory using (say) Flask-Cache, so that its data are available between requests. I thought the data themselves were static, but I think the fact that they are OpenCV keypoint-detector objects (e.g. SIFT, SURF, ORB etc.) means that their addresses are changing between requests - and it's these objects that are creating problems for the caching.

main.py:

# Run as
# python main.py

from flask import Flask, jsonify
from flask_cache import Cache
import backer
app = Flask(__name__)

@app.route('/get-result')
def get_result():
    cached_results = backer.do_some_work()
    return jsonify({'response': cached_results})

if __name__ == "__main__":
    app.run(host='localhost', port=8080, debug=True, threaded=True)

In backer.py I have:

import time

from flask import Flask
from flask_cache import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})

import cv2
import numpy as np

@cache.cached(timeout=300, key_prefix='all_comments')
def get_all_comments():
    comments = range(10000)
    time.sleep(2)  # do_serious_dbio()
    print 'cache complete'

    if not cache.get('detector'):
        detector = cv2.ORB_create()
        cache.set('detector',detector)
    else:
        detector = cache.get('detector')

    return comments, detector

def do_some_work():
    cached, detector = get_all_comments()

    work_done = [2.0 * c for c in cached]

    print detector

    image = np.random.randint(255, size=(128, 128, 3), dtype=np.uint8)
    kp, des = detector.detectAndCompute(image, None)

    return work_done

On the first request, all is well:

curl http://localhost:8080/get-result

On the second request I get:

    kp, des = detector.detectAndCompute(image, None)
TypeError: Incorrect type of self (must be 'Feature2D' or its derivative)

Note that the detector changes its address between requests, e.g.

<ORB 0x121976070>
<ORB 0x10fc74fb0>

(i) Are the two related?

(ii) Is there a way for Flask to cache an arbitrary object like the OpenCV ORB instance (correct address and all)? or

(iii) Must I somehow serialize/pickle the keypoints, descriptors and other attributes of the ORB objects? or

(iv) Is there another way round, cf e.g. Saving OpenCV object in memory in python ?

Thanks as ever

来源:https://stackoverflow.com/questions/55474340/python-flask-opencv-how-do-i-cache-an-arbitrary-opencv-object-between-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!