1+ import cv2
2+ import tensorflow as tf
3+ from tensorflow .keras .models import Sequential
4+ from tensorflow .keras .layers import Dense , Conv2D , MaxPool2D , Flatten , Activation
5+ from sklearn .model_selection import train_test_split
6+ import numpy as np
7+ import matplotlib .pyplot as plt
8+
9+ import glob
10+ import os
11+
12+ # after you extract the dataset,
13+ # put cell_images folder in the working directory
14+ img_dir = "cell_images"
15+ img_size = 70
16+
17+ def load_img_data (path ):
18+ image_files = glob .glob (os .path .join (path , "Parasitized/*.png" )) + \
19+ glob .glob (os .path .join (path , "Uninfected/*.png" ))
20+ X , y = [], []
21+ for image_file in image_files :
22+ # 0 for uninfected and 1 for infected
23+ label = 0 if "Uninfected" in image_file else 1
24+ # load the image in gray scale
25+ img_arr = cv2 .imread (image_file , cv2 .IMREAD_GRAYSCALE )
26+ # resize the image to (70x70)
27+ img_resized = cv2 .resize (img_arr , (img_size , img_size ))
28+ X .append (img_resized )
29+ y .append (label )
30+ return X , y
31+
32+ # load the data
33+ X , y = load_img_data (img_dir )
34+ # reshape to (n_samples, 70, 70, 1) (to fit the NN)
35+ X = np .array (X ).reshape (- 1 , img_size , img_size , 1 )
36+ # scale pixels from the range [0, 255] to [0, 1]
37+ # to help the neural network learn much faster
38+ X = X / 255
39+
40+ # shuffle & split the dataset
41+ X_train , X_test , y_train , y_test = train_test_split (X , y , test_size = 0.1 , stratify = y )
42+ print ("Total training samples:" , X_train .shape )
43+ print ("Total validation samples:" , X_test .shape [0 ])
44+
45+ model = Sequential ()
46+ model .add (Conv2D (64 , (3 , 3 ), input_shape = X_train .shape [1 :]))
47+ model .add (Activation ("relu" ))
48+ model .add (MaxPool2D (pool_size = (2 , 2 )))
49+
50+ model .add (Conv2D (64 , (3 , 3 )))
51+ model .add (Activation ("relu" ))
52+ model .add (MaxPool2D (pool_size = (2 , 2 )))
53+
54+ model .add (Conv2D (64 , (3 , 3 )))
55+ model .add (Activation ("relu" ))
56+ model .add (MaxPool2D (pool_size = (2 , 2 )))
57+
58+ model .add (Flatten ())
59+
60+ model .add (Dense (64 ))
61+ model .add (Activation ("relu" ))
62+
63+ model .add (Dense (64 ))
64+ model .add (Activation ("relu" ))
65+
66+ model .add (Dense (1 ))
67+ model .add (Activation ("sigmoid" ))
68+
69+ model .compile (loss = "binary_crossentropy" , optimizer = "adam" , metrics = ["accuracy" ])
70+
71+ # train the model with 3 epochs, 64 batch size
72+ model .fit (X_train , np .array (y_train ), batch_size = 64 , epochs = 3 , validation_split = 0.2 )
73+ # if you already trained the model, uncomment below and comment above
74+ # so you can only load the previously trained model
75+ # model.load_weights("malaria-cell-cnn.h5")
76+
77+ loss , accuracy = model .evaluate (X_test , np .array (y_test ), verbose = 0 )
78+ print (f"Testing on { len (X_test )} images, the results are\n Accuracy: { accuracy } | Loss: { loss } " )
79+
80+ # save the model & weights
81+ model .save ("malaria-cell-cnn.h5" )
82+
83+ # testing some images
84+ uninfected_cell = "cell_images/testing-samples/C1_thinF_IMG_20150604_104919_cell_82.png"
85+ infected_cell = "cell_images/testing-samples/C38P3thinF_original_IMG_20150621_112116_cell_204.png"
86+
87+ _ , ax = plt .subplots (1 , 2 )
88+ ax [0 ].imshow (plt .imread (uninfected_cell ))
89+ ax [0 ].title .set_text ("Uninfected Cell" )
90+ ax [1 ].imshow (plt .imread (infected_cell ))
91+ ax [1 ].title .set_text ("Parasitized Cell" )
92+ plt .show ()
93+
94+ img_arr_uninfected = cv2 .imread (uninfected_cell , cv2 .IMREAD_GRAYSCALE )
95+ img_arr_infected = cv2 .imread (infected_cell , cv2 .IMREAD_GRAYSCALE )
96+ # resize the images to (70x70)
97+ img_arr_uninfected = cv2 .resize (img_arr_uninfected , (img_size , img_size ))
98+ img_arr_infected = cv2 .resize (img_arr_infected , (img_size , img_size ))
99+ # scale to [0, 1]
100+ img_arr_infected = img_arr_infected / 255
101+ img_arr_uninfected = img_arr_uninfected / 255
102+ # reshape to fit the neural network dimensions
103+ # (changing shape from (70, 70) to (1, 70, 70, 1))
104+ img_arr_infected = img_arr_infected .reshape (1 , * img_arr_infected .shape )
105+ img_arr_infected = np .expand_dims (img_arr_infected , axis = 3 )
106+ img_arr_uninfected = img_arr_uninfected .reshape (1 , * img_arr_uninfected .shape )
107+ img_arr_uninfected = np .expand_dims (img_arr_uninfected , axis = 3 )
108+ # perform inference
109+ infected_result = model .predict (img_arr_infected )[0 ][0 ]
110+ uninfected_result = model .predict (img_arr_uninfected )[0 ][0 ]
111+ print (f"Infected: { infected_result } " )
112+ print (f"Uninfected: { uninfected_result } " )
0 commit comments