Python/OpenCV:如何在请求之间缓存任意(OpenCV)对象?

2024-04-24 09:35:58 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码片段中,我有一个常用的Flask应用程序,它从另一个python模块(也在下面)调用一个函数。你知道吗

我想要一个(慢的/昂贵的/任意的)函数被缓存在内存中使用(比如说)Flask Cache,以便它的数据在请求之间可用。我认为数据本身是静态的,但我认为它们是OpenCV keypoint detector对象(例如SIFT、SURF、ORB等)这一事实意味着它们的地址在请求之间发生变化——正是这些对象给缓存带来了问题。你知道吗

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)

backer.py我有:

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

根据第一个要求,一切都很好:

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

在第二个请求中,我得到:

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

请注意,detector在请求之间更改其地址,例如

<ORB 0x121976070>
<ORB 0x10fc74fb0>

(一)两者有关联吗?你知道吗

(ii)有没有一种方法可以让Flask缓存任意对象,比如OpenCV ORB实例(正确的地址和全部)?或者

(iii)我必须以某种方式序列化/pickle ORB对象的关键点、描述符和其他属性吗?或者

(iv)是否有另一种方法,例如Saving OpenCV object in memory in python?你知道吗

一如既往地谢谢你


Tags: 对象fromimportappflaskcachegetdetector