Hussein El-Hadidy commited on
Commit
7a47e4d
·
1 Parent(s): 8a8b504

Classifier Added

Browse files
Files changed (4) hide show
  1. SkinBurns_Classification.py +65 -0
  2. app.py +73 -16
  3. requirements.txt +2 -1
  4. svm_model.pkl +3 -0
SkinBurns_Classification.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ from skimage.feature import local_binary_pattern, graycomatrix, graycoprops
5
+ from sklearn.svm import SVC
6
+ from sklearn.model_selection import train_test_split
7
+ from sklearn.metrics import classification_report, accuracy_score
8
+ import glob
9
+ import matplotlib.pyplot as plt
10
+ from sklearn.preprocessing import StandardScaler
11
+ import pickle
12
+
13
+ # Parameters for feature extraction
14
+ LBP_RADIUS = 1
15
+ LBP_POINTS = 8 * LBP_RADIUS
16
+ GLCM_DISTANCES = [1, 2, 3] # Increased distances
17
+ GLCM_ANGLES = [0, np.pi/4, np.pi/2, 3*np.pi/4] # Increased angles
18
+ scaler = StandardScaler()
19
+
20
+ def extract_color_histogram(image, bins=(4, 4, 4)):
21
+ """Extract color histogram features from an image."""
22
+ hist = cv2.calcHist([image], [0, 1, 2], None, bins, [0, 256, 0, 256, 0, 256])
23
+ cv2.normalize(hist, hist)
24
+ return hist.flatten()
25
+
26
+ def extract_lbp_features(image, radius=LBP_RADIUS, points=LBP_POINTS):
27
+ """Extract Local Binary Pattern (LBP) features from an image."""
28
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
29
+ lbp = local_binary_pattern(gray, points, radius, method='uniform')
30
+ (hist, _) = np.histogram(lbp.ravel(), bins=np.arange(0, points + 3), range=(0, points + 2))
31
+ hist = hist.astype('float')
32
+ hist /= (hist.sum() + 1e-6)
33
+ return hist
34
+
35
+ def extract_glcm_features(image, distances=GLCM_DISTANCES, angles=GLCM_ANGLES):
36
+ """Extract Gray-Level Co-occurrence Matrix (GLCM) features from an image."""
37
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
38
+ glcm = graycomatrix(gray, distances=distances, angles=angles, symmetric=True, normed=True)
39
+ features = []
40
+ for prop in ['contrast', 'dissimilarity', 'homogeneity', 'energy', 'correlation']:
41
+ feature = graycoprops(glcm, prop)
42
+ features.extend(feature.flatten())
43
+ return np.array(features)
44
+
45
+ def extract_invariant_moments(image):
46
+ """Extract invariant moment features from an image."""
47
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
48
+ moments = cv2.moments(gray)
49
+ hu_moments = cv2.HuMoments(moments).flatten()
50
+ return hu_moments
51
+
52
+
53
+
54
+ def extract_features(image_path):
55
+ """Extract combined features from an image."""
56
+ image = cv2.imread(image_path)
57
+ if image is None:
58
+ print(f"Warning: Unable to read image at {image_path}")
59
+ return None
60
+ color_hist = extract_color_histogram(image)
61
+ lbp_features = extract_lbp_features(image)
62
+ glcm_features = extract_glcm_features(image)
63
+ invariant_moments = extract_invariant_moments(image)
64
+ return np.hstack([color_hist, lbp_features, glcm_features, invariant_moments])
65
+
app.py CHANGED
@@ -1,10 +1,15 @@
 
 
1
  from fastapi import FastAPI, File, UploadFile
 
2
  from pymongo.mongo_client import MongoClient
3
  from pymongo.server_api import ServerApi
4
  import cloudinary
5
  import cloudinary.uploader
6
  from cloudinary.utils import cloudinary_url
 
7
  from SkinBurns_Segmentation import segment_skin_burns
 
8
 
9
  app = FastAPI()
10
 
@@ -57,32 +62,84 @@ async def upload_sample(file: UploadFile = File(...)):
57
  return {"uploaded_url": uploaded_url}
58
  except Exception as e:
59
  return {"error": str(e)}
60
-
61
- @app.post("/skin_burns/segment")
62
- async def Segment_Burns(file: UploadFile = File(...), output_path='segmented_image.png'):
 
63
  try:
64
- # Save the uploaded file temporarily
65
- with open(file.filename, "wb") as temp_file:
66
- temp_file.write(await file.read())
67
 
68
- # Call the segmentation function
69
- segmented_image_path = segment_skin_burns(file.filename, output_path)
 
 
 
70
 
71
- # Upload the segmented image to Cloudinary
72
- result = cloudinary.uploader.upload(segmented_image_path, public_id=f"segmented_{file.filename}")
73
- uploaded_url = result["secure_url"]
74
 
75
- # Save segmented image URL to MongoDB
76
- collection = db["Images"]
77
- doc = {"filename": f"segmented_{file.filename}", "url": uploaded_url}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  collection.insert_one(doc)
79
 
80
- return {"segmented_image_url": uploaded_url}
 
 
 
 
81
  except Exception as e:
82
- return {"error": str(e)}
83
 
 
 
 
 
 
 
 
 
 
 
 
84
 
 
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
 
88
 
 
1
+ import os
2
+ import pickle
3
  from fastapi import FastAPI, File, UploadFile
4
+ from fastapi.responses import JSONResponse
5
  from pymongo.mongo_client import MongoClient
6
  from pymongo.server_api import ServerApi
7
  import cloudinary
8
  import cloudinary.uploader
9
  from cloudinary.utils import cloudinary_url
10
+ from SkinBurns_Classification import extract_features
11
  from SkinBurns_Segmentation import segment_skin_burns
12
+ import requests
13
 
14
  app = FastAPI()
15
 
 
62
  return {"uploaded_url": uploaded_url}
63
  except Exception as e:
64
  return {"error": str(e)}
65
+
66
+
67
+ @app.post("/skin_burns/predict")
68
+ async def predict_burn(file: UploadFile = File(...)):
69
  try:
70
+ # Upload to Cloudinary
71
+ upload_result = cloudinary.uploader.upload(file.file, public_id=f"predict_{file.filename}")
72
+ cloudinary_url = upload_result["secure_url"]
73
 
74
+ # Download the image from Cloudinary
75
+ response = requests.get(cloudinary_url)
76
+ temp_image_path = f"predict_{file.filename}"
77
+ with open(temp_image_path, 'wb') as out_file:
78
+ out_file.write(response.content)
79
 
80
+ # Load the trained SVM model
81
+ with open('svm_model.pkl', 'rb') as model_file:
82
+ loaded_svm = pickle.load(model_file)
83
 
84
+ # Extract features from the downloaded image
85
+ features = extract_features(temp_image_path)
86
+
87
+ # Delete temporary image file
88
+ os.remove(temp_image_path)
89
+
90
+ if features is None:
91
+ return JSONResponse(content={"error": "Failed to extract features from the image."}, status_code=400)
92
+
93
+ # Reshape and predict
94
+ features = features.reshape(1, -1)
95
+ prediction = loaded_svm.predict(features)
96
+ prediction_label = "Burn" if prediction[0] == 1 else "No Burn"
97
+
98
+ #Save result to MongoDB (if needed)
99
+ collection = db["Predictions"]
100
+ doc = {"filename": file.filename, "url": cloudinary_url, "prediction": prediction_label}
101
  collection.insert_one(doc)
102
 
103
+ return {
104
+ "prediction": prediction_label,
105
+ "image_url": cloudinary_url
106
+ }
107
+
108
  except Exception as e:
109
+ return JSONResponse(content={"error": str(e)}, status_code=500)
110
 
111
+ @app.post("/predict_burn")
112
+ async def predict_burn(file: UploadFile = File(...)):
113
+ try:
114
+ # Save the uploaded file temporarily
115
+ temp_file_path = f"temp_{file.filename}"
116
+ with open(temp_file_path, "wb") as temp_file:
117
+ temp_file.write(await file.read())
118
+
119
+ # Load the saved SVM model
120
+ with open('svm_model.pkl', 'rb') as model_file:
121
+ loaded_svm = pickle.load(model_file)
122
 
123
+ # Extract features from the uploaded image
124
+ features = extract_features(temp_file_path)
125
 
126
+ # Remove the temporary file
127
+ os.remove(temp_file_path)
128
+
129
+ if features is None:
130
+ return JSONResponse(content={"error": "Failed to extract features from the image."}, status_code=400)
131
+
132
+ # Reshape features to match the SVM model's expected input
133
+ features = features.reshape(1, -1)
134
+
135
+ # Predict the class
136
+ prediction = loaded_svm.predict(features)
137
+ prediction_label = "Burn" if prediction[0] == 1 else "No Burn"
138
+
139
+ return {"prediction": prediction_label}
140
+
141
+ except Exception as e:
142
+ return JSONResponse(content={"error": str(e)}, status_code=500)
143
 
144
 
145
 
requirements.txt CHANGED
@@ -9,4 +9,5 @@ scipy
9
  tensorly
10
  scikit-learn
11
  opencv-python
12
- matplotlib
 
 
9
  tensorly
10
  scikit-learn
11
  opencv-python
12
+ matplotlib
13
+ glob2
svm_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:acf55c90d6a4067d1a83c0e15764fb47b0197a1f2cfa2abccb580260eff0316a
3
+ size 337615