-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathgenerate_index.py
58 lines (46 loc) · 1.58 KB
/
generate_index.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python
# coding=utf-8
"""
Time : 2018-11-18
Author : Mousse
email: zibuyu1995@gmail.com
"""
import asyncio
import glob
import ujson
from concurrent.futures import ProcessPoolExecutor
import uvloop
from tinydb import TinyDB
from config.config import dataset_path, cpu_count, image_bins
from mlibs.hsv_features import get_image_feature
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
def feature_persistence(task_results: list) -> int:
""" 图像特征集持久化到key-value数据库 """
feature_dict = dict(task_result.result() for task_result in task_results)
db = TinyDB('./static/dataset.db')
table = db.table('feature')
table.insert(feature_dict)
feature_count = len(feature_dict)
return feature_count
async def generate_image_index(eve_loop, processes_executor):
""" 多进程生成图像索引 """
image_feature_tasks = []
task_append = image_feature_tasks.append
for image_path in glob.glob(dataset_path + "/*.png"):
task_append(
eve_loop.run_in_executor(
processes_executor, get_image_feature, image_path, image_bins
)
)
task_results, _ = await asyncio.wait(image_feature_tasks)
feature_count = feature_persistence(task_results)
print(f"{feature_count}幅图像完成索引")
if __name__ == '__main__':
executor = ProcessPoolExecutor(max_workers=cpu_count)
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(
generate_image_index(event_loop, executor)
)
finally:
event_loop.close()