-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_image_db.py
86 lines (75 loc) · 2.1 KB
/
create_image_db.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import sqlite3
from PIL import Image
import os
import base64
import random
import argparse
import numpy as np
from io import BytesIO
from glob import glob
from tqdm import tqdm
MAX_HEIGHT = 15000
MAX_WIDTH = 20000
parser = argparse.ArgumentParser(description='Create SQLite image database.')
parser.add_argument('--input_path',dest="input_path",type=str,
help='path to folder containing images')
parser.add_argument('--output_path',dest="output_path",type=str,
help='path to SQLite output')
args = parser.parse_args()
conn = sqlite3.connect(args.output_path)
try:
conn.execute("DROP TABLE images;")
conn.execute("DROP TABLE slide_labels;")
conn.execute("DROP TABLE metadata;")
conn.execute("DROP TABLE labels;")
except:
pass
sql = '''
create table if not exists images(
id integer primary key autoincrement,
picture blob,
name text);
'''
conn.execute(sql)
sql = '''
create table if not exists labels(
picture_id integer primary key,
label text,
user_id text);
'''
conn.execute(sql)
sql ='''
create table if not exists metadata(
id integer primary key autoincrement,
number_of_images integer);
'''
conn.execute(sql)
i = 0
for image_path in tqdm(glob(args.input_path + '/*')):
image = Image.open(image_path)
if image.size[0] > MAX_HEIGHT:
rescale_factor = image.size[0] / MAX_HEIGHT
size = [0,0]
size[0] = MAX_HEIGHT
size[1] = int(image.size[1]/rescale_factor)
image = image.resize(size)
if image.size[1] > MAX_WIDTH:
rescale_factor = image.size[1] / MAX_WIDTH
size = [0,0]
size[1] = MAX_WIDTH
size[0] = int(image.size[0]/rescale_factor)
image = image.resize(size)
i += 1
with BytesIO() as bio:
image.save(bio,format='JPEG')
ablob = base64.b64encode(bio.getvalue())
sql = '''INSERT INTO images
(picture, name)
VALUES(?, ?);'''
conn.execute(sql,[sqlite3.Binary(ablob), image_path])
conn.commit()
sql = '''INSERT INTO metadata
(number_of_images)
VALUES(?);'''
conn.execute(sql,[i])
conn.commit()