{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install pillow","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import PIL\nprint('Pillow Version:', PIL.__version__)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from PIL import Image\nimg1= Image.open(\"../input/cassava-leaf-disease-classification/train_images/1000015157.jpg\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(img1.format,img1.size,img1.mode)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Converting images into numpy arrays and back**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# load and display an image with Matplotlib\nfrom matplotlib import image\nfrom matplotlib import pyplot\n# load image as pixel array\ndata = image.imread('../input/cassava-leaf-disease-classification/train_images/1000201771.jpg')\n# summarize shape of the pixel array\nprint(data.dtype)\nprint(data.shape)\n# display the array of pixels as an image\npyplot.imshow(data)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Loads the photo as a Pillow Image object and converts it to a NumPy array, then converts it back to an Image object again.**"},{"metadata":{"trusted":true},"cell_type":"code","source":"from PIL import Image\nfrom numpy import asarray\n# load the image\nimage = Image.open('../input/cassava-leaf-disease-classification/train_images/100042118.jpg')\ndata = asarray(image)\n# summarize shape\nprint(data.shape)\n# create Pillow image\nimage2 = Image.fromarray(data)\n# summarize image details\nprint(image2.format)\nprint(image2.mode)\nprint(image2.size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pyplot.imshow(image2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# load and display an image with Matplotlib\nfrom matplotlib import image\nfrom matplotlib import pyplot\n# load image as pixel array\ndata = image.imread('../input/cassava-leaf-disease-classification/train_images/1000910826.jpg')\n# summarize shape of the pixel array\nprint(data.dtype)\nprint(data.shape)\n# display the array of pixels as an image\npyplot.imshow(data)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# load and display an image with Matplotlib\nfrom matplotlib import image\nfrom matplotlib import pyplot\n# load image as pixel array\ndata = image.imread('../input/cassava-leaf-disease-classification/train_images/1004826518.jpg')\nprint(data.dtype)\nprint(data.shape)\n# display the array of pixels as an image\npyplot.imshow(data)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Resizing Images**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# create a thumbnail of an image\nfrom PIL import Image\n# load the image\nimage = Image.open('../input/cassava-leaf-disease-classification/train_images/1004826518.jpg')\nprint(image.size)\n# create a thumbnail and preserve aspect ratio\nimage.thumbnail((100,100))\n# report the size of the thumbnail\nprint(image.size)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":" Resize a new image and ignore the original aspect ratio."},{"metadata":{"trusted":true},"cell_type":"code","source":"image = Image.open('../input/cassava-leaf-disease-classification/train_images/1004163647.jpg')\n# report the size of the image\nprint(image.size)\n# resize image and ignore original aspect ratio\nimg_resized = image.resize((200,200))\n# report the size of the thumbnail\nprint(img_resized.size)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Flipping, Rotating and Cropping images\n**Flipping Image**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# load image\nimage = Image.open('../input/cassava-leaf-disease-classification/train_images/1004881261.jpg')\n# horizontal flip\nhoz_flip = image.transpose(Image.FLIP_LEFT_RIGHT)\n# vertical flip\nver_flip = image.transpose(Image.FLIP_TOP_BOTTOM)\n# plot all three images using matplotlib\npyplot.subplot(311)\npyplot.imshow(image)\npyplot.subplot(312)\npyplot.imshow(hoz_flip)\npyplot.subplot(313)\npyplot.imshow(ver_flip)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Rotating Image**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# load image\nimage = Image.open('../input/cassava-leaf-disease-classification/train_images/1005739807.jpg')\n# plot original image\npyplot.subplot(311)\npyplot.imshow(image)\n# rotate 45 degrees\npyplot.subplot(312)\npyplot.imshow(image.rotate(45))\n# rotate 90 degrees\npyplot.subplot(313)\npyplot.imshow(image.rotate(90))\npyplot.show()\n#rotates 270 degrees\npyplot.imshow(image.rotate(270))\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Cropping Images**"},{"metadata":{"trusted":true},"cell_type":"code","source":"from PIL import Image\n# load image\nimage = Image.open('../input/cassava-leaf-disease-classification/train_images/1017006970.jpg')\n# create a cropped image\ncropped = image.crop((100, 100, 370, 280))\n# show cropped image\npyplot.imshow(cropped)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.utils import to_categorical\nfrom keras.layers import BatchNormalization\nfrom keras.preprocessing import image\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/cassava-leaf-disease-classification/train.csv')    # reading the csv file\ntrain.head()  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head(20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.tail()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.columns","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Loads Image and training set resized"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_image = []\nfor i in tqdm(range(3000)):\n    img = image.load_img('../input/cassava-leaf-disease-classification/train_images/'+train['image_id'][i], target_size=(200,200,3), grayscale=False)\n    img = image.img_to_array(img)\n    img = img/255\n    train_image.append(img)\nX = np.array(train_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X[17])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X[35])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X[60])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X[2])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X[69])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X[86])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y=train[0:3000]['label'].values\ny = to_categorical(y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=45, test_size=0.10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Deep learning model from scratch"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(filters=128, kernel_size=(3, 3), activation=\"relu\", input_shape=(200,200,3)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(filters=128, kernel_size=(3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(filters=128, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(5, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(X_train, y_train, epochs=50, validation_data=(X_test, y_test), batch_size=64, verbose=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from matplotlib import pyplot\n# plot history\npyplot.plot(history.history['accuracy'], label='train')\npyplot.plot(history.history['val_accuracy'], label='test')\npyplot.legend()\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nimport numpy as np\nimg = cv2.imread('../input/cassava-leaf-disease-classification/test_images/2216849948.jpg')\nplt.imshow(img)\nimg = cv2.resize(img,(200, 200))\nimg = np.reshape(img,[1,200, 200,3])\nclasses = model.predict_classes(img)\nprint(classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores = model.evaluate(X_test, y_test, verbose=0)\nprint(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights(\"model.h5\")\nprint(\"Saved model to disk\")","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}