APJ23 commited on
Commit
28e7100
·
1 Parent(s): 84fcebe

Delete hw3(1).py

Browse files
Files changed (1) hide show
  1. hw3 (1).py +0 -62
hw3 (1).py DELETED
@@ -1,62 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """HW3.ipynb
3
-
4
- Automatically generated by Colaboratory.
5
-
6
- Original file is located at
7
- https://colab.research.google.com/drive/1H-R9L74rpYOoQJOnTLLbUpcNpd9Tty_D
8
- """
9
-
10
- !wget http://vis-www.cs.umass.edu/lfw/lfw.tgz
11
- !tar -xvf /content/lfw.tgz
12
- import tensorflow as tf
13
- from sklearn.datasets import load_sample_image
14
- import os
15
- import tensorflow.keras.applications.resnet50 as resnet50
16
- from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
17
- from tensorflow.keras.preprocessing.image import load_img, img_to_array
18
- import numpy as np
19
- from PIL import Image
20
- from sklearn.neighbors import NearestNeighbors
21
-
22
- directory = '/content/lfw'
23
- model = resnet50.ResNet50(weights='imagenet', include_top=False, pooling='avg')
24
- feature_dict = {}
25
- image_files = []
26
- target_size = (224, 224)
27
- i = 0
28
-
29
- # Sample at most 2000 images because the whole entire dataset
30
- # costs too much cpu power and ram
31
-
32
- def preprocess_image(image_path, target_size):
33
- img = load_img(os.path.join(directory,image_path),target_size=target_size)
34
- x = img_to_array(img)
35
- x = tf.expand_dims(x, axis = 0)
36
- x = preprocess_input(x)
37
- features = model.predict(x)
38
- return features
39
-
40
- for dir in os.listdir(directory):
41
- i += 1
42
- new_dir = '/content/lfw/'+dir
43
- if os.path.isdir(new_dir):
44
- for files in os.listdir(new_dir):
45
- feature_dict[new_dir+'/'+files] = preprocess_image(new_dir+'/'+files, target_size).flatten()
46
- if i >= 100:
47
- break
48
-
49
- for file, features in feature_dict.items():
50
- print(file, features)
51
-
52
- feature_map = np.array(list(feature_dict.values()))
53
-
54
- NearNeigh = NearestNeighbors(n_neighbors=10,algorithm='auto').fit(feature_map)
55
-
56
- for image_path in feature_dict:
57
- img = feature_dict[image_path].reshape(1,-1)
58
- distance,indices = NearNeigh.kneighbors(img)
59
- print('Similar images for', image_path)
60
- for i, index in enumerate(indices[0]):
61
- similar_img_path = list(feature_dict.keys())[index]
62
- print(i+1,similar_img_path)