-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_library.py
77 lines (62 loc) · 2.33 KB
/
image_library.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
"""
A library for all functions image-related
"""
import cv2
import numpy as np
from scipy.misc import imread
import glob
# list of images features for all images in data/small_album_images
def create_image_feature_array():
images = glob.glob('data/large_album_images/*.jpg')
feature_array = [get_image_features(img) for img in images]
return np.array(feature_array)
# Turn an image file into an array of features, returns 0s if fails
def get_image_features(image_path, vector_size=200, img=None,):
features = extract_features(image_path, vector_size, img)
if(check_size(features)):
return features
else:
features = resize_array(features)
return features
# ensures array is size 200*64
def resize_array(array):
num_vectors = len(array)
for v in range(num_vectors):
# ensure all vectors are length 64
v_size = len(array[v])
if(v_size < 64):
array[v] = np.concatenate([array[v], np.zeros(64 - v_size)])
# ensures 200 vectors
if(num_vectors < 200):
zero_vector = [np.zeros(64) for i in range(200-num_vectors)]
array = np.concatenate([array, zero_vector])
return array
# returns True if array is correct size, else False
def check_size(array):
correct_size = True
if(len(array) != 200):
correct_size = False
for v in range(len(array)):
if(len(array[v]) != 64):
correct_size = False
return correct_size
# returns feature list of size 200*64
def extract_features(image_path, vector_size=200, img=None):
image = img if img is not None else imread(image_path, mode="RGB")
try:
alg = cv2.KAZE_create()
# Finding image keypoints
kps = alg.detect(image)
# Getting first 200 of them.
# Number of keypoints is varies depend on image size and color pallet
# Sorting them based on keypoint response value(bigger is better)
kps = sorted(kps, key=lambda x: -x.response)[:vector_size]
# computing descriptors vector
if(len(kps) > 0):
kps, dsc = alg.compute(image, kps)
else:
dsc = [[0]*64 for i in range(200)]
except cv2.error as e:
print('Error: ', e)
return [np.zeros(64) for i in range(200)]
return dsc