-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeature_extraction.py
More file actions
57 lines (48 loc) · 2.1 KB
/
Copy pathfeature_extraction.py
File metadata and controls
57 lines (48 loc) · 2.1 KB
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
import torch
from torchvision import models, transforms
from PIL import Image
import os
import numpy as np
# Load pre-trained ResNet model
model = models.resnet50(weights="IMAGENET1K_V1") # Updated to match the new API
model = torch.nn.Sequential(*list(model.children())[:-1]) # Remove classification layer
model.eval()
# Define image transformations
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# Function to extract features from an image
def extract_features(image_path):
image = Image.open(image_path).convert('RGB')
image = transform(image).unsqueeze(0) # Add batch dimension
with torch.no_grad():
features = model(image).squeeze().numpy() # Flatten the output
return features
# Extract features from all .jpg files in a folder
def extract_features_from_folder(folder_path):
feature_list = []
image_paths = []
for root, _, files in os.walk(folder_path):
for file in files:
if file.lower().endswith('.jpg'):
image_path = os.path.join(root, file)
features = extract_features(image_path)
print(f"Processed: {image_path}, Feature shape: {features.shape}") # Debugging print
feature_list.append(features)
image_paths.append(image_path)
# Convert to numpy array for clustering
features_array = np.array(feature_list)
print(f"Total number of images processed: {len(feature_list)}")
print(f"Feature array shape: {features_array.shape}")
return features_array, image_paths
if __name__ == "__main__":
folder_path = "jay1-others" # Change this to your folder path
features, paths = extract_features_from_folder(folder_path)
if features.size == 0:
print("No features extracted. Please check your image paths.")
else:
np.save("features.npy", features) # Save features for clustering
np.save("paths.npy", paths) # Save paths for later reference
print("Feature extraction complete.")