Whale Detection based on Arieal Images¶
Credit: AITS Cainvas Community
This will help drones in identifying whales when they surface
In [1]:
#!wget -N "https://cainvas-static.s3.amazonaws.com/media/user_data/cainvas-admin/Final_Whale_Dataset.zip" -O Final_Whale_Dataset.zip
#!unzip -qo Final_Whale_Dataset.zip
In [2]:
import cv2
import matplotlib.pyplot as plt
import seaborn as sns
import os
from PIL import Image
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.utils import to_categorical
import numpy as np
import os
In [3]:
Whales = os.listdir("Final Whale Dataset/Yes/")
Not_whales = os.listdir("Final Whale Dataset/No/")
In [4]:
Whales[:10]
Out[4]:
In [5]:
Not_whales[:10]
Out[5]:
Looking at the Dataset¶
Here we have used whales for positive and other animals as negative
In [6]:
plt.figure(figsize = (12,12))
for i in range(4):
plt.subplot(1, 4, i+1)
img = cv2.imread("Final Whale Dataset/Yes/" + Whales[i])
plt.imshow(img)
plt.title('Whales : 1')
plt.tight_layout()
plt.show()
In [7]:
plt.figure(figsize = (12,12))
for i in range(4):
plt.subplot(1, 4, i+1)
img = cv2.imread('Final Whale Dataset/No/'+ Not_whales[i+1])
plt.imshow(img)
plt.title('Not Whale : 0')
plt.tight_layout()
plt.show()
Creating Training and Validation¶
In [8]:
data = []
labels = []
for img in Whales:
try:
img_read = plt.imread('Final Whale Dataset/Yes/' + img)
img_resize = cv2.resize(img_read, (50, 50))
img_array = img_to_array(img_resize)
data.append(img_array)
labels.append(1)
except:
None
for img in Not_whales:
try:
img_read = plt.imread('Final Whale Dataset/No/' + img)
img_resize = cv2.resize(img_read, (50, 50))
img_array = img_to_array(img_resize)
data.append(img_array)
labels.append(0)
except:
None
In [9]:
image_data = np.array(data)
labels = np.array(labels)
In [10]:
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(image_data, labels, test_size = 0.33, random_state = 101)
In [11]:
x_train = x_train/255
x_test = x_test/255
In [12]:
y_train = to_categorical(y_train, num_classes = 2)
y_test = to_categorical(y_test, num_classes = 2)
In [13]:
print(f'SHAPE OF TRAINING IMAGE DATA : {x_train.shape}')
print(f'SHAPE OF TESTING IMAGE DATA : {x_test.shape}')
print(f'SHAPE OF TRAINING LABELS : {y_train.shape}')
print(f'SHAPE OF TESTING LABELS : {y_test.shape}')
Creating Model¶
In [14]:
from tensorflow.keras.layers import Dense, Conv2D
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import MaxPooling2D, GlobalAveragePooling2D
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras import backend as K
from tensorflow.keras import optimizers
In [15]:
def CNNbuild(height, width, classes, channels):
model = Sequential()
inputShape = (height, width, channels)
chanDim = -1
if K.image_data_format() == 'channels_first':
inputShape = (channels, height, width)
model.add(Conv2D(32, (3,3), activation = 'relu', input_shape = inputShape))
model.add(MaxPooling2D(2,2))
model.add(BatchNormalization(axis = chanDim))
model.add(Conv2D(32, (3,3), activation = 'relu'))
model.add(MaxPooling2D(2,2))
model.add(BatchNormalization(axis = chanDim))
model.add(Conv2D(32, (3,3), activation = 'relu'))
model.add(MaxPooling2D(2,2))
model.add(BatchNormalization(axis = chanDim))
model.add(Flatten())
model.add(Dense(8, activation = 'relu'))
model.add(Dense(8, activation = 'relu'))
model.add(Dense(8, activation = 'relu'))
model.add(BatchNormalization(axis = chanDim))
model.add(Dropout(0.5))
model.add(Dense(classes, activation = 'softmax'))
return model
In [16]:
height = 50
width = 50
classes = 2
channels = 3
model = CNNbuild(height = height, width = width, classes = classes, channels = channels)
model.summary()
In [17]:
model.compile(loss = 'categorical_crossentropy', optimizer = 'Adam', metrics = ['accuracy'])
In [18]:
h = model.fit(x_train, y_train, validation_data=(x_test,y_test), epochs = 20, batch_size = 32)
PLotting Graph¶
In [19]:
plt.figure(figsize = (15,5))
plt.plot(range(20), h.history['accuracy'], label = 'Training Accuracy')
plt.plot(range(20), h.history['loss'], label = 'Taining Loss')
plt.plot(range(20), h.history['val_accuracy'], label = 'Taining Loss')
#ax1.set_xticks(np.arange(0, 31, 5))
plt.xlabel("Number of Epoch's")
plt.ylabel('Accuracy/Loss Value')
plt.title('Training Accuracy and Training Loss')
plt.legend(loc = "best")
Out[19]:
In [20]:
predictions = model.evaluate(x_test, y_test)
In [21]:
print(f'LOSS : {predictions[0]}')
print(f'ACCURACY : {predictions[1]}')
In [22]:
model.save("Whales.h5")
Prediction¶
In [23]:
plt.figure(figsize = (12,12))
img = cv2.imread("Final Whale Dataset/Yes/" + Whales[4])
img_resize = cv2.resize(img, (50, 50))
plt.subplot(1, 4, i+1)
plt.imshow(img)
output = model.predict(np.expand_dims(img_resize,0))[0][0] # getting output; input shape (64, 64, 3) --> (1, 64, 64, 1)
print(output)
pred = (output > 0.5).astype('int')
print("Predicted: ", labels, '(', output, '-->', pred, ')') # Picking the label from class_names base don the model output
plt.title('Whales : 0')
plt.tight_layout()
In [24]:
plt.figure(figsize = (12,12))
img = cv2.imread("Final Whale Dataset/Yes/" + Whales[6])
img_resize = cv2.resize(img, (50, 50))
plt.subplot(1, 4, i+1)
plt.imshow(img)
output = model.predict(np.expand_dims(img_resize,0))[0][0] # getting output; input shape (64, 64, 3) --> (1, 64, 64, 1)
print(output)
pred = (output > 0.5).astype('int')
print("Predicted: ", labels, '(', output, '-->', pred, ')') # Picking the label from class_names base don the model output
plt.title('Whales : 0')
plt.tight_layout()
DeepCC¶
In [ ]:
!deepCC