Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import os
import glob
import cv2
import numpy as np
from skimage.feature import local_binary_pattern
from sklearn.neighbors import KDTree

# Constants
IMG_SIZE = (128, 128)

# ------------------------------
# Feature Extraction Function
# ------------------------------
def extract_features(image):
image = cv2.resize(image, IMG_SIZE)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Color Histogram (RGB)
hist = cv2.calcHist([image], [0, 1, 2], None, [8, 8, 8],
[0, 256, 0, 256, 0, 256])
hist = cv2.normalize(hist, hist).flatten()

# LBP Texture
lbp = local_binary_pattern(gray, P=8, R=1, method='uniform')
(lbp_hist, _) = np.histogram(lbp.ravel(),
bins=np.arange(0, 11),
range=(0, 10))
lbp_hist = lbp_hist.astype("float")
lbp_hist /= (lbp_hist.sum() + 1e-7)

return np.hstack([hist, lbp_hist])


# ------------------------------
# Dataset Loader + KDTree Builder
# ------------------------------
def load_dataset_and_build_kdtree(dataset_path):
features_list = []
labels_list = []
label_map = {}
label_names = sorted(os.listdir(dataset_path))

for idx, disease_folder in enumerate(label_names):
full_path = os.path.join(dataset_path, disease_folder)
if not os.path.isdir(full_path):
continue

label_clean = disease_folder.split(' ')[0].strip().lower().replace(' ', '_')
label_map[idx] = label_clean

for ext in ('*.jpg', '*.jpeg', '*.png'):
for img_path in glob.glob(os.path.join(full_path, ext)):
try:
img = cv2.imread(img_path)
if img is None:
continue
feat = extract_features(img)
features_list.append(feat)
labels_list.append(idx)
except Exception as e:
print(f"Error with {img_path}: {e}")

features_array = np.array(features_list)
labels_array = np.array(labels_list)

if len(features_array) > 0:
tree = KDTree(features_array)
print(f"✅ KD-Tree built with {features_array.shape[0]} feature vectors.")
return tree, features_array, labels_array, label_map
else:
print("⚠️ No features extracted. Please check your image folder paths and formats.")
return None, None, None, None
26 changes: 26 additions & 0 deletions Team 104- Skin Disease Analysis/core/feature_extraction/loading.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# import numpy as np
# from sklearn.neighbors import KDTree
# import pickle

# def load_features_and_tree(path='features_tree.pkl'):
# with open(path, 'rb') as f:
# data = pickle.load(f)
# return data['tree'], data['features'], data['labels'], data['label_map']

import pickle
import numpy as np

def load_kdtree():
with open('kdtree.pkl', 'rb') as f:
tree = pickle.load(f)
return tree

def load_features():
return np.load('features.npy')

def load_labels():
return np.load('labels.npy')

def load_label_map():
with open('label_map.pkl', 'rb') as f:
return pickle.load(f)
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import csv
import heapq

# Global dictionary to store per-disease severity weights
SEVERITY_WEIGHTS = {}

def load_severity_weights(csv_path='data/severity_weights.csv'):
global SEVERITY_WEIGHTS
with open(csv_path, mode='r', encoding='utf-8') as file:
reader = csv.DictReader(file)
for row in reader:
disease = row["Disease"].strip()
SEVERITY_WEIGHTS[disease] = {
"pain_level": float(row["pain_level"]),
"itching_level": float(row["itching_level"]),
"duration_days": float(row["duration_days"]),
"area_factor": float(row["area_factor"]),
"fever_present": float(row["fever_present"]),
"bleeding": float(row["bleeding"]),
"spread_rate_factor": float(row["spread_rate_factor"]),
}

class SeverityScorer:
def __init__(self):
self.heap = [] # Heap of (score, disease)
self.direct_scores = {} # Optional raw score addition

def add_raw_score(self, disease, score):
"""Add precomputed score (e.g., from image similarity)"""
self.direct_scores[disease] = self.direct_scores.get(disease, 0) + score

def calculate_and_add_score(self, disease, pain_level, itching_level, duration_days, max_duration,
area_factor, fever_present, bleeding, spread_rate_factor):
"""
Calculates weighted severity using global SEVERITY_WEIGHTS.
"""
if disease not in SEVERITY_WEIGHTS:
return

weights = SEVERITY_WEIGHTS[disease]
score = (
weights.get("pain_level", 0) * (pain_level / 10) +
weights.get("itching_level", 0) * (itching_level / 10) +
weights.get("duration_days", 0) * (duration_days / max_duration if max_duration else 0) +
weights.get("area_factor", 0) * area_factor +
weights.get("fever_present", 0) * int(fever_present) +
weights.get("bleeding", 0) * int(bleeding) +
weights.get("spread_rate_factor", 0) * spread_rate_factor
)

heapq.heappush(self.heap, (round(score, 4), disease))

def get_most_severe(self):
if self.heap:
return heapq.nlargest(1, self.heap)[0]
if self.direct_scores:
return max(self.direct_scores.items(), key=lambda x: x[1])
return None

def get_all_ranked(self):
if self.heap:
return heapq.nlargest(len(self.heap), self.heap)
return sorted(self.direct_scores.items(), key=lambda x: x[1], reverse=True)
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
self.diseases = set()

class SymptomTrie:
def __init__(self):
self.root = TrieNode()

def insert(self, symptom, disease):
node = self.root
for char in symptom.lower():
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
node.diseases.add(disease)

def search(self, prefix):
node = self.root
for char in prefix.lower():
if char in node.children:
node = node.children[char]
else:
return set()
return self._collect_diseases(node)

def _collect_diseases(self, node):
results = set(node.diseases)
for child in node.children.values():
results.update(self._collect_diseases(child))
return results
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import csv

class TreatmentMap:
def __init__(self, csv_path):
self.map = {}
with open(csv_path, mode='r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
disease = row['Disease'].strip()
treatments = [t.strip() for t in row['Recommended Treatment'].split(',')]
self.map[disease] = treatments # Disease as key, list of treatments as value

def get_treatment(self, disease_name):
# Get the list of treatments for a given disease name
return self.map.get(disease_name, ["Consult a specialist for tailored treatment."])

def match_symptoms(self, input_symptoms):
# Match input symptoms to diseases and return diseases with common symptoms
input_set = set(s.strip().lower() for s in input_symptoms.split(','))
matches = []

for disease in self.map.keys():
# Placeholder: Add symptom matching logic here
matches.append(disease)

return matches
11 changes: 11 additions & 0 deletions Team 104- Skin Disease Analysis/data/disease_info.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Disease,Common Symptoms,Severity Level,Recommended Treatment,ICD-10 Code
Eczema,"Dry skin, itching, red patches, inflammation, scaling, crusting, redness, cracked skin, swelling",Moderate,"Topical corticosteroids, moisturizers, antihistamines",L20.9
"Warts, Molluscum, and other Viral Infections","Raised bumps, rough texture, small flesh-colored growths, sometimes itchy or painful, small bumps, brown growths, itching",Mild,"Cryotherapy, salicylic acid, topical antivirals",B07.9
Melanoma,"New or changing mole, asymmetry, irregular borders, varied colors, bleeding, itching",Severe,"Surgical excision, immunotherapy, targeted therapy",C43.9
Atopic Dermatitis,"Intense itching, dry scaly skin, red inflamed patches, especially in folds of skin, itching, rashes, swelling, crusting",Moderate,"Topical steroids, emollients, immunomodulators",L20.0
Basal Cell Carcinoma (BCC),"Pearly or waxy bump, flat flesh-colored lesion, bleeding sore that doesn't heal, scaly area",Severe,"Mohs surgery, radiation therapy, topical chemo",C44.91
Melanocytic Nevi (NV),"Small and dark brown spots, flat or raised moles, typically uniform in shape and color, ",Mild,"Observation, excision if suspicious or for cosmetic reasons",D22.9
Benign Keratosis-like Lesions (BKL),"Waxy or wart-like growth, brown/tan/black, scaly surface, can be flat or slightly raised",Mild,"Cryotherapy, curettage, laser removal",L82.1
"Psoriasis, Lichen Planus, and related diseases","Thick red patches with silvery scales, purple flat-topped bumps, severe itching, cracked skin",Moderate to Severe,"Topical corticosteroids, phototherapy, biologics",L40.9
Seborrheic Keratoses and other Benign Tumors,"Brown/black growths, waxy/stuck-on appearance, generally painless, ",Mild,"Cryosurgery, curettage, no treatment if asymptomatic",L82.0
"Tinea, Ringworm, Candidiasis, and other Fungal Infections","Red circular rashes, itching, peeling skin, white patches in mouth or moist areas, scaling, cracking skin",Moderate,"Topical antifungals, oral antifungals in severe cases",B35.9
13 changes: 13 additions & 0 deletions Team 104- Skin Disease Analysis/data/disease_labels.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"Disease_0": "Eczema",
"Disease_1": "Warts, Molluscum, and other Viral Infections",
"Disease_2": "Melanoma",
"Disease_3": "Atopic Dermatitis",
"Disease_4": "Basal Cell Carcinoma (BCC)",
"Disease_5": "Melanocytic Nevi (NV)",
"Disease_6": "Benign Keratosis-like Lesions (BKL)",
"Disease_7": "Psoriasis, Lichen Planus, and related diseases",
"Disease_8": "Seborrheic Keratoses and other Benign Tumors",
"Disease_9": "Tinea, Ringworm, Candidiasis, and other Fungal Infections"
}

11 changes: 11 additions & 0 deletions Team 104- Skin Disease Analysis/data/severity_weights.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Disease,pain_level,itching_level,duration_days,area_factor,fever_present,bleeding,spread_rate_factor
Eczema,0.15,0.25,0.1,0.2,0.05,0.1,0.15
"Warts, Molluscum, and other Viral Infections",0.2,0.1,0.1,0.25,0.05,0.1,0.2
Melanoma,0.1,0.05,0.1,0.2,0.2,0.15,0.2
Atopic Dermatitis,0.1,0.3,0.1,0.15,0.05,0.1,0.2
Basal Cell Carcinoma (BCC),0.15,0.1,0.15,0.2,0.1,0.15,0.15
Melanocytic Nevi (NV),0.05,0.05,0.1,0.3,0.05,0.1,0.35
Benign Keratosis-like Lesions (BKL),0.05,0.1,0.1,0.25,0.05,0.15,0.3
"Psoriasis, Lichen Planus, and related diseases",0.1,0.25,0.1,0.2,0.05,0.1,0.2
Seborrheic Keratoses and other Benign Tumors,0.05,0.1,0.1,0.25,0.05,0.1,0.35
"Tinea, Ringworm, Candidiasis, and other Fungal Infections",0.1,0.25,0.1,0.2,0.05,0.05,0.25
Loading