top of page
  • Writer's pictureHackers Realm

Dogs vs Cats Image Classification using Python | CNN | Deep Learning Project Tutorial

Updated: 1 day ago

Embark on the journey of image classification with Python! This tutorial explores CNN and deep learning techniques to classify images of dogs and cats. Learn to build accurate models that can distinguish between these furry friends, unlocking applications in pet recognition, animal monitoring, and more. Enhance your skills in computer vision, deep learning, and unleash the power of image classification. Join this comprehensive project tutorial to unravel the world of dogs vs cats image classification. #DogsVsCats #Python #CNN #DeepLearning #ImageClassification #ComputerVision

Dogs Vs Cats Image Classification
Dogs Vs Cats Image Classification

In this project tutorial we will use Convolutional Neural Network (CNN) for image feature extraction and visualize the results with plot graphs.


You can watch the video-based tutorial with step by step explanation down below.


Dataset Information


The training archive contains 25,000 images of dogs and cats. Train your algorithm on these files and predict the labels


(1 = dog, 0 = cat).


Download the dataset here


Environment: Google Colab



Download Dataset


We can download the dataset directly from the Microsoft page

!wget https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zipa

--2021-05-06 16:04:20-- https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip Resolving download.microsoft.com (download.microsoft.com)... 23.78.216.154, 2600:1417:8000:980::e59, 2600:1417:8000:9b2::e59 Connecting to download.microsoft.com (download.microsoft.com)|23.78.216.154|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 824894548 (787M) [application/octet-stream] Saving to: ‘kagglecatsanddogs_3367a.zip’ kagglecatsanddogs_3 100%[===================>] 786.68M 187MB/s in 4.3s 2021-05-06 16:04:24 (183 MB/s) - ‘kagglecatsanddogs_3367a.zip’ saved [824894548/824894548]


Unzip the Dataset

!unzip kagglecatsanddogs_3367a.zip
  • Run this code once and comment it


Import Modules


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
import os
import tqdm
import random
from keras.preprocessing.image import load_img
warnings.filterwarnings('ignore')
  • pandas - used to perform data manipulation and analysis

  • numpy - used to perform a wide variety of mathematical operations on arrays

  • matplotlib - used for data visualization and graphical plotting

  • os - used to handle files using system commands

  • tqdm - progress bar decorator for iterators

  • random - used for randomizing

  • load_img - used for loading the image as numpy array

  • warnings - to manipulate warnings details, filterwarnings('ignore') is to ignore the warnings thrown by the modules (gives clean results)


Create Dataframe for Input and Output


The Dogs vs Cats dataset may differ from where it was downloaded like folder structures or labels. You may create a dataframe to convert the input and output paths accordingly for easier processing.


input_path = []
label = []

for class_name in os.listdir("PetImages"):
    for path in os.listdir("PetImages/"+class_name):
        if class_name == 'Cat':
            label.append(0)
        else:
            label.append(1)
        input_path.append(os.path.join("PetImages", class_name, path))
print(input_path[0], label[0])

PetImages/Dog/4253.jpg 1

  • Adding the label to the images, one (1) for dogs and zero (0) for cats

  • Display the path of first image with corresponding label


Now we create the dataframe for processing

df = pd.DataFrame()
df['images'] = input_path
df['label'] = label
df = df.sample(frac=1).reset_index(drop=True)
df.head()
Dog Vs Cat Dataset
Dog Vs Cat Dataset
  • Display of image paths with labels

  • Data was shuffled and the index was removed


We must remove any files in the data set that are not image data to avoid errors

for i in df['images']:
    if '.jpg' not in i:
        print(i)

PetImages/Cat/Thumbs.db PetImages/Dog/Thumbs.db



import PIL
l = []
for image in df['images']:
    try:
        img = PIL.Image.open(image)
    except:
        l.append(image)
l

['PetImages/Cat/666.jpg', 'PetImages/Cat/Thumbs.db', 'PetImages/Dog/Thumbs.db', 'PetImages/Dog/11702.jpg']

  • List of non-image type files and corrupted images

# delete db files
df = df[df['images']!='PetImages/Dog/Thumbs.db']
df = df[df['images']!='PetImages/Cat/Thumbs.db']
df = df[df['images']!='PetImages/Cat/666.jpg']
df = df[df['images']!='PetImages/Dog/11702.jpg']
len(df)

24998

  • Dropping the corrupted files and non-image files from the dataset



Exploratory Data Analysis


Let us display a grid of images to know the content of the data

# to display grid of images
plt.figure(figsize=(25,25))
temp = df[df['label']==1]['images']
start = random.randint(0, len(temp))
files = temp[start:start+25]

for index, file in enumerate(files):
    plt.subplot(5,5, index+1)
    img = load_img(file)
    img = np.array(img)
    plt.imshow(img)
    plt.title('Dogs')
    plt.axis('off')
Sample Dog Images
Sample Dog Images
Sample Dog Images
Sample Dog Images
Sample Dog Images
Sample Dog Images
  • Display of 25 random images of dogs

  • plt.axis('off') turns off both axis from the images

  • Files loaded and stored in an array


# to display grid of images
plt.figure(figsize=(25,25))
temp = df[df['label']==0]['images']
start = random.randint(0, len(temp))
files = temp[start:start+25]

for index, file in enumerate(files):
    plt.subplot(5,5, index+1)
    img = load_img(file)
    img = np.array(img)
    plt.imshow(img)
    plt.title('Cats')
    plt.axis('off')
Sample Cat Images
Sample Cat Images
Sample Cat Images
Sample Cat Images
Sample Cat Images
Sample Cat Images
  • Display of 25 random images of cats

  • Different saturation and qualities among the images


import seaborn as sns
sns.countplot(df['label'])
Distribution of Labels
  • seaborn - built on top of matplotlib with similar functionalities

  • We can observe an equal distribution of both classes


Create Data Generator for the Images


Data Generators loads the data from the disk for reading and training the data directly, saving RAM space and avoiding possible overflow that might crash the system.


df['label'] = df['label'].astype('str')
df.head()
Dog Vs Cat Dataset
  • Convert the data type of 'label' to string for easier processing


Let us split the input data

# input split
from sklearn.model_selection import train_test_split
train, test = train_test_split(df, test_size=0.2, random_state=42)


from keras.preprocessing.image import ImageDataGenerator
train_generator = ImageDataGenerator(
    rescale = 1./255,  # normalization