|
import os |
|
import glob |
|
import numpy as np |
|
import seaborn as sns |
|
import matplotlib.pyplot as plt |
|
import pandas as pd |
|
from sklearn.model_selection import train_test_split |
|
from keras_preprocessing.image import ImageDataGenerator |
|
from keras.models import Sequential |
|
from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Flatten |
|
from keras.applications import ResNet50 |
|
from keras.applications.resnet50 import preprocess_input |
|
from sklearn.metrics import classification_report |
|
|
|
import zipfile |
|
import os |
|
|
|
|
|
zip_file = 'dataset.zip' |
|
|
|
|
|
with zipfile.ZipFile(zip_file, 'r') as zip_ref: |
|
zip_ref.extractall('blood_group_dataset') |
|
|
|
|
|
|
|
|
|
for root, dirs, files in os.walk('blood_group_dataset'): |
|
print(root) |
|
for file in dirs: |
|
print(' ', file) |
|
|
|
import os |
|
import glob |
|
import pandas as pd |
|
import seaborn as sns |
|
import matplotlib.pyplot as plt |
|
|
|
|
|
filepaths = [] |
|
labels = [] |
|
|
|
for root, dirs, files in os.walk('blood_group_dataset'): |
|
for dir in dirs: |
|
for file in glob.glob(os.path.join(root, dir, '*')): |
|
filepaths.append(file) |
|
labels.append(dir) |
|
|
|
|
|
filepath = pd.Series(filepaths, name='Filepath').astype(str) |
|
Labels = pd.Series(labels, name='Label') |
|
data = pd.concat([filepath, Labels], axis=1) |
|
data = data.sample(frac=1).reset_index(drop=True) |
|
|
|
|
|
|
|
filtered_data = data[data['Label'] != 'dataset'] |
|
|
|
|
|
counts = filtered_data.Label.value_counts() |
|
sns.barplot(x=counts.index, y=counts) |
|
plt.xlabel('Blood Group Type') |
|
plt.ylabel('Number of Images') |
|
plt.xticks(rotation=90) |
|
plt.title('Class Distribution in Blood Group Dataset') |
|
plt.show() |
|
|
|
|
|
train, test = train_test_split(data, test_size=0.20, random_state=42) |
|
|
|
|
|
fig, axes = plt.subplots(nrows=5, ncols=3, figsize=(10, 8), subplot_kw={'xticks': [], 'yticks': []}) |
|
for i, ax in enumerate(axes.flat): |
|
ax.imshow(plt.imread(data.Filepath[i])) |
|
ax.set_title(data.Label[i]) |
|
plt.tight_layout() |
|
plt.show() |
|
|
|
|
|
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input) |
|
test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input) |
|
|
|
train_gen = train_datagen.flow_from_dataframe( |
|
dataframe=train, |
|
x_col='Filepath', |
|
y_col='Label', |
|
target_size=(224, 224), |
|
class_mode='categorical', |
|
batch_size=32, |
|
shuffle=True, |
|
seed=42 |
|
) |
|
|
|
valid_gen = test_datagen.flow_from_dataframe( |
|
dataframe=test, |
|
x_col='Filepath', |
|
y_col='Label', |
|
target_size=(224, 224), |
|
class_mode='categorical', |
|
batch_size=32, |
|
shuffle=False, |
|
seed=42 |
|
) |
|
|
|
|
|
model = Sequential([ |
|
Conv2D(6, kernel_size=(5, 5), activation='relu', input_shape=(224, 224, 3)), |
|
MaxPooling2D(pool_size=(2, 2)), |
|
Conv2D(16, kernel_size=(5, 5), activation='relu'), |
|
MaxPooling2D(pool_size=(2, 2)), |
|
Flatten(), |
|
Dense(120, activation='relu'), |
|
Dense(84, activation='relu'), |
|
Dense(8, activation='softmax') |
|
]) |
|
|
|
model.compile( |
|
optimizer="adam", |
|
loss='categorical_crossentropy', |
|
metrics=['accuracy'] |
|
) |
|
|
|
|
|
history = model.fit( |
|
train_gen, |
|
validation_data=valid_gen, |
|
epochs=20 |
|
) |
|
|
|
|
|
pd.DataFrame(history.history)[['accuracy', 'val_accuracy']].plot() |
|
plt.title("Accuracy") |
|
plt.show() |
|
|
|
|
|
pd.DataFrame(history.history)[['loss', 'val_loss']].plot() |
|
plt.title("Loss") |
|
plt.show() |
|
|
|
|
|
results = model.evaluate(valid_gen, verbose=0) |
|
print(f"Test Loss: {results[0]:.5f}") |
|
print(f"Test Accuracy: {results[1]*100:.2f}%") |
|
|
|
|
|
pred = model.predict(valid_gen) |
|
pred = np.argmax(pred, axis=1) |
|
|
|
|
|
labels = train_gen.class_indices |
|
labels = dict((v, k) for k, v in labels.items()) |
|
pred = [labels[k] for k in pred] |
|
|
|
|
|
|
|
y_test = list(test.Label) |
|
|
|
y_test = y_test[:len(pred)] |
|
|
|
print(classification_report(y_test, pred)) |
|
|
|
model.save("model_blood_group_detection_lenet.keras") |
|
|
|
import numpy as np |
|
import matplotlib.pyplot as plt |
|
from keras.models import load_model |
|
from keras.preprocessing import image |
|
from keras.applications.imagenet_utils import preprocess_input |
|
|
|
|
|
model = load_model('model_blood_group_detection_lenet.keras') |
|
|
|
|
|
labels = {'A+': 0, 'A-': 1, 'AB+': 2, 'AB-': 3, 'B+': 4, 'B-': 5, 'O+': 6, 'O-': 7} |
|
labels = dict((v, k) for k, v in labels.items()) |
|
|
|
|
|
img_path = 'augmented_cluster_4_3505.BMP' |
|
|
|
|
|
img = image.load_img(img_path, target_size=(224, 224)) |
|
x = image.img_to_array(img) |
|
x = np.expand_dims(x, axis=0) |
|
x = preprocess_input(x) |
|
|
|
|
|
result = model.predict(x) |
|
predicted_class = np.argmax(result) |
|
|
|
|
|
predicted_label = labels[predicted_class] |
|
confidence = result[0][predicted_class] * 100 |
|
|
|
|
|
plt.imshow(image.array_to_img(image.img_to_array(img) / 255.0)) |
|
plt.axis('off') |
|
|
|
|
|
plt.title(f"Prediction: {predicted_label} with confidence {confidence:.2f}%") |
|
plt.show() |
|
|
|
|