annaferrari02 commited on
Commit
0fcd8ae
·
verified ·
1 Parent(s): 42372fa

upload files

Browse files
.gitattributes CHANGED
@@ -1,35 +1,35 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ---
2
+ license: mit
3
+ ---
multiclass_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92bea164e635928131fd50dc8760709cc1b7eae5c8bb62d1077dde21e53af102
3
+ size 1548622
pca_params.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb51cb2295694f77311dba09515b2b5a17edd1073e5a5f1186054c1d123050fc
3
+ size 23793014
script.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference script
3
+ Version combining baseline structure with enhanced features
4
+ """
5
+
6
+ import os
7
+ import pickle
8
+ import cv2
9
+ import pandas as pd
10
+ import numpy as np
11
+ from utils.utils import extract_features_from_image, apply_pca_transform
12
+
13
+
14
+ def run_inference(TEST_IMAGE_PATH, svm_model, pca_params, SUBMISSION_CSV_SAVE_PATH):
15
+ """
16
+ Run inference on test images
17
+
18
+ Args:
19
+ TEST_IMAGE_PATH: Path to test images (/tmp/data/test_images)
20
+ svm_model: Trained SVM model
21
+ pca_params: Dictionary containing PCA transformation parameters
22
+ SUBMISSION_CSV_SAVE_PATH: Path to save submission.csv
23
+ """
24
+
25
+ # Load test images
26
+ test_images = os.listdir(TEST_IMAGE_PATH)
27
+ test_images.sort()
28
+
29
+ # Extract features from all test images
30
+ image_feature_list = []
31
+
32
+ for test_image in test_images:
33
+ path_to_image = os.path.join(TEST_IMAGE_PATH, test_image)
34
+
35
+ image = cv2.imread(path_to_image)
36
+
37
+ # Extract features (using enhanced features by default)
38
+ image_features = extract_features_from_image(image)
39
+
40
+ image_feature_list.append(image_features)
41
+
42
+ features_array = np.array(image_feature_list)
43
+
44
+ # Apply PCA transformation using saved parameters
45
+ features_reduced = apply_pca_transform(features_array, pca_params)
46
+
47
+ # Run predictions
48
+ predictions = svm_model.predict(features_reduced)
49
+
50
+ # Create submission CSV
51
+ df_predictions = pd.DataFrame({
52
+ "file_name": test_images,
53
+ "category_id": predictions
54
+ })
55
+
56
+ df_predictions.to_csv(SUBMISSION_CSV_SAVE_PATH, index=False)
57
+
58
+
59
+ if __name__ == "__main__":
60
+
61
+ # Paths
62
+ current_directory = os.path.dirname(os.path.abspath(__file__))
63
+ TEST_IMAGE_PATH = "/tmp/data/test_images"
64
+
65
+ MODEL_NAME = "multiclass_model.pkl"
66
+ MODEL_PATH = os.path.join(current_directory, MODEL_NAME)
67
+
68
+ PCA_PARAMS_NAME = "pca_params.pkl"
69
+ PCA_PARAMS_PATH = os.path.join(current_directory, PCA_PARAMS_NAME)
70
+
71
+ SUBMISSION_CSV_SAVE_PATH = os.path.join(current_directory, "submission.csv")
72
+
73
+ # Load trained SVM model
74
+ with open(MODEL_PATH, 'rb') as file:
75
+ svm_model = pickle.load(file)
76
+
77
+ # Load PCA parameters
78
+ with open(PCA_PARAMS_PATH, 'rb') as file:
79
+ pca_params = pickle.load(file)
80
+
81
+ # Run inference
82
+ run_inference(TEST_IMAGE_PATH, svm_model, pca_params, SUBMISSION_CSV_SAVE_PATH)
train.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Training script for surgical instrument classification
3
+ """
4
+
5
+ import os
6
+ import pickle
7
+ import cv2
8
+ import pandas as pd
9
+ import numpy as np
10
+ from utils.utils import extract_features_from_image, fit_pca_transformer, train_svm_model
11
+
12
+
13
+ def train_and_save_model(base_path, images_folder, gt_csv, save_dir, n_components=100):
14
+ """
15
+ Complete training pipeline that saves everything needed for submission
16
+
17
+ Args:
18
+ base_path: Base directory path
19
+ images_folder: Folder name containing images
20
+ gt_csv: Ground truth CSV filename
21
+ save_dir: Directory to save model artifacts
22
+ n_components: Number of PCA components
23
+ """
24
+
25
+ print("="*80)
26
+ print("TRAINING SURGICAL INSTRUMENT CLASSIFIER")
27
+ print("="*80)
28
+
29
+ # Setup paths
30
+ PATH_TO_GT = os.path.join(base_path, gt_csv)
31
+ PATH_TO_IMAGES = os.path.join(base_path, images_folder)
32
+
33
+ print(f"\nConfiguration:")
34
+ print(f" Ground Truth: {PATH_TO_GT}")
35
+ print(f" Images: {PATH_TO_IMAGES}")
36
+ print(f" PCA Components: {n_components}")
37
+ print(f" Save directory: {save_dir}")
38
+
39
+ # Load ground truth
40
+ df = pd.read_csv(PATH_TO_GT)
41
+ print(f"\nLoaded {len(df)} training samples")
42
+ print(f"\nLabel distribution:")
43
+ print(df['category_id'].value_counts().sort_index())
44
+
45
+ # Extract features
46
+ print(f"\n{'='*80}")
47
+ print("STEP 1: FEATURE EXTRACTION")
48
+ print("="*80)
49
+
50
+ features = []
51
+ labels = []
52
+
53
+ for i in range(len(df)):
54
+ if i % 500 == 0:
55
+ print(f" Processing {i}/{len(df)}...")
56
+
57
+ image_name = df.iloc[i]["file_name"]
58
+ label = df.iloc[i]["category_id"]
59
+
60
+ path_to_image = os.path.join(PATH_TO_IMAGES, image_name)
61
+
62
+ try:
63
+ image = cv2.imread(path_to_image)
64
+ if image is None:
65
+ print(f" Warning: Could not read {image_name}, skipping...")
66
+ continue
67
+
68
+ # Extract features with enhanced configuration
69
+ image_features = extract_features_from_image(image)
70
+
71
+ features.append(image_features)
72
+ labels.append(label)
73
+
74
+ except Exception as e:
75
+ print(f" Error processing {image_name}: {e}")
76
+ continue
77
+
78
+ features_array = np.array(features)
79
+ labels_array = np.array(labels)
80
+
81
+ print(f"\nFeature extraction complete!")
82
+ print(f" Features shape: {features_array.shape}")
83
+ print(f" Labels shape: {labels_array.shape}")
84
+ print(f" Feature dimension: {features_array.shape[1]}")
85
+
86
+ # Apply PCA
87
+ print(f"\n{'='*80}")
88
+ print("STEP 2: DIMENSIONALITY REDUCTION (PCA)")
89
+ print("="*80)
90
+
91
+ pca_params, features_reduced = fit_pca_transformer(features_array, n_components)
92
+
93
+ print(f" Reduced from {features_array.shape[1]} to {n_components} dimensions")
94
+ print(f" Explained variance: {pca_params['cumulative_variance'][-1]:.4f}")
95
+
96
+ # Train SVM
97
+ print(f"\n{'='*80}")
98
+ print("STEP 3: TRAINING SVM CLASSIFIER")
99
+ print("="*80)
100
+
101
+ train_results = train_svm_model(features_reduced, labels_array)
102
+
103
+ svm_model = train_results['model']
104
+
105
+ print(f"\nTraining complete!")
106
+ print(f" Support vectors: {len(svm_model.support_)}")
107
+
108
+ # Save model artifacts
109
+ print(f"\n{'='*80}")
110
+ print("STEP 4: SAVING MODEL ARTIFACTS")
111
+ print("="*80)
112
+
113
+ os.makedirs(save_dir, exist_ok=True)
114
+
115
+ # Save SVM model
116
+ model_path = os.path.join(save_dir, "multiclass_model.pkl")
117
+ with open(model_path, "wb") as f:
118
+ pickle.dump(svm_model, f)
119
+ print(f" ✓ Saved SVM model: {model_path}")
120
+
121
+ # Save PCA parameters
122
+ pca_path = os.path.join(save_dir, "pca_params.pkl")
123
+ with open(pca_path, "wb") as f:
124
+ pickle.dump(pca_params, f)
125
+ print(f" ✓ Saved PCA params: {pca_path}")
126
+
127
+ print(f"\n{'='*80}")
128
+ print("TRAINING COMPLETE!")
129
+ print("="*80)
130
+ print(f"\nFiles saved to: {save_dir}")
131
+ print(f"\nNext steps:")
132
+ print(f" 1. Create a 'utils' folder in your HuggingFace repository")
133
+ print(f" 2. Copy utils.py into the 'utils' folder")
134
+ print(f" 3. Copy script.py, multiclass_model.pkl, and pca_params.pkl to the repository root")
135
+ print(f" 4. Create an empty __init__.py file in the 'utils' folder")
136
+ print(f" 5. Submit to competition!")
137
+
138
+
139
+ if __name__ == "__main__":
140
+
141
+ BASE_PATH = "C:/Users/anna2/ISM/ANNA/phase1a-wavelet"
142
+ IMAGES_FOLDER = "C:/Users/anna2/ISM/Images"
143
+ GT_CSV = "C:/Users/anna2/ISM/Baselines/phase_1a/gt_for_classification_multiclass_from_filenames_0_index.csv"
144
+
145
+ SAVE_DIR = "C:/Users/anna2/ISM/ANNA/phase1a-wavelet/submission"
146
+
147
+ # Number of PCA components
148
+ N_COMPONENTS = 250 #can be adjusted
149
+
150
+ # Train and save
151
+ train_and_save_model(BASE_PATH, IMAGES_FOLDER, GT_CSV, SAVE_DIR, N_COMPONENTS)
utils/__pycache__/utils.cpython-312.pyc ADDED
Binary file (12.9 kB). View file
 
utils/utils.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for surgical instrument classification
3
+ """
4
+
5
+ import cv2
6
+ import numpy as np
7
+ from skimage.feature.texture import graycomatrix, graycoprops
8
+ from skimage.feature import local_binary_pattern, hog
9
+ from sklearn.decomposition import PCA
10
+ from sklearn.svm import SVC
11
+ from sklearn.model_selection import train_test_split
12
+ from sklearn.metrics import accuracy_score, f1_score
13
+ import pywt
14
+
15
+ def preprocess_image(image):
16
+ """
17
+ Apply CLAHE preprocessing for better contrast
18
+ (Contrast Limited Adaptive Historam Equalization)
19
+ """
20
+ # Convert to LAB color space (basically separating lightness, L, from color info)
21
+ lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
22
+ l, a, b = cv2.split(lab) #this enhances constrast between colors
23
+
24
+ # Apply CLAHE to L channel
25
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) #split into a 8x8 grid and performs the contrast enhancement to the smaller regions instead of full image
26
+ l = clahe.apply(l)
27
+
28
+ # Merge and convert back
29
+ enhanced = cv2.merge([l, a, b]) #merge the contrast channel with the other two (A,B)
30
+ enhanced = cv2.cvtColor(enhanced, cv2.COLOR_LAB2BGR) #go back to BGR so it can be used later on
31
+
32
+ return enhanced
33
+
34
+
35
+ #this is the same as baseline code, well working so let's keep it
36
+ #it basically computes normalized color histograms for the classic three channels
37
+ def rgb_histogram(image, bins=256):
38
+ """Extract RGB histogram features"""
39
+ hist_features = []
40
+ for i in range(3): # RGB Channels
41
+ hist, _ = np.histogram(image[:, :, i], bins=bins, range=(0, 256), density=True)
42
+ hist_features.append(hist)
43
+ return np.concatenate(hist_features)
44
+
45
+
46
+ def hu_moments(image):
47
+ """Extract Hu moment features, takes BGR format in input
48
+ basically provides shape description that are consistent
49
+ wrt to position, size and rotation"""
50
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #turn to greyscale (works in 1 channel)
51
+ moments = cv2.moments(gray)
52
+ hu_moments = cv2.HuMoments(moments).flatten()
53
+ return hu_moments
54
+
55
+
56
+ def glcm_features(image, distances=[1], angles=[0], levels=256, symmetric=True, normed=True):
57
+ """Extract GLCM texture features,
58
+ captures texture info considering spatial
59
+ relationship between pixel intensities. works well with RGB and hu"""
60
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
61
+ glcm = graycomatrix(gray, distances=distances, angles=angles, levels=levels,
62
+ symmetric=symmetric, normed=normed)
63
+ contrast = graycoprops(glcm, 'contrast').flatten()
64
+ dissimilarity = graycoprops(glcm, 'dissimilarity').flatten()
65
+ homogeneity = graycoprops(glcm, 'homogeneity').flatten()
66
+ energy = graycoprops(glcm, 'energy').flatten()
67
+ correlation = graycoprops(glcm, 'correlation').flatten()
68
+ asm = graycoprops(glcm, 'ASM').flatten()
69
+ return np.concatenate([contrast, dissimilarity, homogeneity, energy, correlation, asm])
70
+
71
+
72
+ def local_binary_pattern_features(image, P=8, R=1):
73
+ """Extract Local Binary Pattern features, useful for light changes
74
+ combined with rgb, hu and glcm"""
75
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
76
+ lbp = local_binary_pattern(gray, P, R, method='uniform')
77
+ (hist, _) = np.histogram(lbp.ravel(), bins=np.arange(0, P + 3),
78
+ range=(0, P + 2), density=True)
79
+ return hist #feature vector representing the texture of the image
80
+
81
+
82
+ def hog_features(image, orientations=12, pixels_per_cell=(16, 16), cells_per_block=(2, 2)):
83
+ """
84
+ Extract HOG (Histogram of Oriented Gradients) features
85
+ Great for capturing shape and edge information in surgical instruments
86
+ """
87
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
88
+
89
+ # Resize to standard size for consistency
90
+ gray_resized = cv2.resize(gray, (256, 256)) #we could try using 256 here and 16,16 cells per block
91
+
92
+ hog_features_vector = hog(
93
+ gray_resized,
94
+ orientations=orientations,
95
+ pixels_per_cell=pixels_per_cell,
96
+ cells_per_block=cells_per_block,
97
+ block_norm='L2-Hys',
98
+ feature_vector=True
99
+ )
100
+
101
+ return hog_features_vector #Returns a vector capturing local edge
102
+ #directions and shape information, useful for detecting instruments,
103
+ #objects, or structural patterns.
104
+
105
+
106
+ def luv_histogram(image, bins=32): #instead of bgr it uses lightness and chromatic components
107
+ """
108
+ Extract histogram in LUV color space
109
+ LUV is perceptually uniform and better for underwater/surgical imaging
110
+ """
111
+ luv = cv2.cvtColor(image, cv2.COLOR_BGR2LUV)
112
+ hist_features = []
113
+ for i in range(3):
114
+ hist, _ = np.histogram(luv[:, :, i], bins=bins, range=(0, 256), density=True)
115
+ hist_features.append(hist)
116
+ return np.concatenate(hist_features)
117
+
118
+
119
+ def gabor_features(image, frequencies=[0.1, 0.2, 0.3],
120
+ orientations=[0, 45, 90, 135]):
121
+ """
122
+ Extract Gabor filter features (gabor kernels)
123
+ texture orientation that deals well with different scales and diff orientation
124
+ """
125
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # uses intensity and not color
126
+ features = []
127
+
128
+ for freq in frequencies:
129
+ for theta in orientations:
130
+ theta_rad = theta * np.pi / 180
131
+ kernel = cv2.getGaborKernel((21, 21), 5, theta_rad,
132
+ 10.0/freq, 0.5, 0)
133
+ filtered = cv2.filter2D(gray, cv2.CV_32F, kernel)
134
+ features.append(np.mean(filtered))
135
+ features.append(np.std(filtered))
136
+
137
+ return np.array(features)
138
+
139
+ def wavelet_features(image, wavelet='db4', levels=3):
140
+
141
+ # try out multi-orientation wavelets (e.g., sym8, coif)
142
+ """
143
+ multi-scale wavelet feature extractor
144
+ focus on texture + edges.
145
+ This function converts an image to grayscale,
146
+ performs a multi-level 2D wavelet decomposition,
147
+ and extracts texture features from the approximation and detail sub-bands.
148
+ It summarizes each band using statistics like mean, standard deviation, and peak magnitude.
149
+ The result is a numerical feature vector capturing multi-scale texture and edge
150
+ information for tasks like surgical tool detection.
151
+ """
152
+
153
+ # Convert to grayscale float32 in [0,1]
154
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY).astype(np.float32) / 255.0
155
+
156
+ # Ensure the decomposition level is valid for this image
157
+ max_level = pywt.dwt_max_level(min(gray.shape), pywt.Wavelet(wavelet).dec_len)
158
+ levels = min(levels, max_level)
159
+
160
+ coeffs = pywt.wavedec2(gray, wavelet=wavelet, level=levels)
161
+
162
+ features = []
163
+
164
+ #Approximation Coefficients (LL)
165
+ LL = coeffs[0]
166
+ LL_abs = np.abs(LL)
167
+ features.extend([
168
+ LL.mean(),
169
+ LL.std(),
170
+ LL_abs.max(),
171
+ LL_abs.mean(),
172
+ ])
173
+
174
+ # Detail Coefficients for each level: (LH, HL, HH)
175
+ for (LH, HL, HH) in coeffs[1:]:
176
+ for band in (LH, HL, HH):
177
+ band_abs = np.abs(band)
178
+ features.extend([
179
+ band_abs.mean(), # energy-like texture measure
180
+ band_abs.std(), # variation in texture
181
+ band_abs.max(), # strongest directional edge
182
+ np.percentile(band_abs, 95), # robust peak measure
183
+ ])
184
+
185
+ return np.array(features, dtype=np.float32)
186
+
187
+
188
+ def extract_features_from_image(image):
189
+ """
190
+ Extract enhanced features from image
191
+ Uses baseline features + HOG + LUV histogram + Gabor for better performance
192
+
193
+ Args:
194
+ image: Input image (BGR format from cv2.imread)
195
+
196
+ Returns:
197
+ Feature vector as numpy array
198
+ """
199
+ # Preprocess image first
200
+ image = preprocess_image(image)
201
+
202
+ # Baseline features
203
+ hist_features = rgb_histogram(image)
204
+ hu_features = hu_moments(image)
205
+ glcm_features_vector = glcm_features(image)
206
+ lbp_features = local_binary_pattern_features(image)
207
+
208
+ # Enhanced features that add discriminative power for complex images
209
+ hog_feat = hog_features(image)
210
+ luv_hist = luv_histogram(image)
211
+ gabor_feat = gabor_features(image)
212
+ wavelet_feat = wavelet_features(image)
213
+
214
+ # Concatenate all features (produces a single vector)
215
+ image_features = np.concatenate([
216
+ hist_features,
217
+ hu_features,
218
+ glcm_features_vector,
219
+ lbp_features,
220
+ hog_feat,
221
+ luv_hist,
222
+ gabor_feat,
223
+ wavelet_feat
224
+ ])
225
+
226
+ return image_features # comprehensive numerical representation of the imag
227
+
228
+
229
+ def fit_pca_transformer(data, num_components):
230
+ """
231
+ Fit a PCA transformer on training data
232
+
233
+ Args:
234
+ data: Training data (n_samples, n_features)
235
+ num_components: Number of PCA components to keep
236
+
237
+ Returns:
238
+ pca_params: Dictionary containing PCA parameters
239
+ data_reduced: PCA-transformed data
240
+ """
241
+
242
+ # Standardize the data
243
+ mean = np.mean(data, axis=0)
244
+ std = np.std(data, axis=0)
245
+
246
+ # Avoid division by zero
247
+ std[std == 0] = 1.0
248
+
249
+ data_standardized = (data - mean) / std
250
+
251
+ # Fit PCA using sklearn
252
+ pca_model = PCA(n_components=num_components)
253
+ data_reduced = pca_model.fit_transform(data_standardized)
254
+
255
+ # Create params dictionary
256
+ pca_params = {
257
+ 'pca_model': pca_model,
258
+ 'mean': mean,
259
+ 'std': std,
260
+ 'num_components': num_components,
261
+ 'feature_dim': data.shape[1],
262
+ 'explained_variance_ratio': pca_model.explained_variance_ratio_,
263
+ 'cumulative_variance': np.cumsum(pca_model.explained_variance_ratio_)
264
+ }
265
+
266
+ return pca_params, data_reduced
267
+
268
+
269
+ def apply_pca_transform(data, pca_params):
270
+ """
271
+ Apply saved PCA transformation to new data
272
+ CRITICAL: This uses the saved mean/std/PCA from training
273
+
274
+ Args:
275
+ data: New data to transform (n_samples, n_features)
276
+ pca_params: Dictionary from fit_pca_transformer
277
+
278
+ Returns:
279
+ Transformed data
280
+ """
281
+
282
+ # Standardize using training mean/std
283
+ data_standardized = (data - pca_params['mean']) / pca_params['std']
284
+
285
+ # Apply PCA transformation
286
+ # Projects new data onto the same principal components computed from training data
287
+ data_reduced = pca_params['pca_model'].transform(data_standardized)
288
+
289
+ return data_reduced
290
+
291
+
292
+ def train_svm_model(features, labels, kernel='rbf', C=1.0):
293
+ """
294
+ Train an SVM model on ALL available data (no train/test split)
295
+
296
+ Args:
297
+ features: Feature matrix (n_samples, n_features)
298
+ labels: Label array (n_samples,)
299
+ kernel: SVM kernel type ('linear', 'rbf', 'poly', 'sigmoid')
300
+ C: Regularization parameter (smaller = more regularization)
301
+
302
+ Returns:
303
+ Dictionary containing model and metrics
304
+ """
305
+
306
+ # Check if labels are one-hot encoded
307
+ if labels.ndim > 1 and labels.shape[1] > 1:
308
+ labels = np.argmax(labels, axis=1)
309
+
310
+ # Train SVM on ALL data
311
+ svm_model = SVC(kernel=kernel, C=C, random_state=56)
312
+ svm_model.fit(features, labels)
313
+
314
+
315
+ results = {
316
+ 'model': svm_model
317
+ }
318
+
319
+ return results