Coding / Programming Videos

Post your favorite coding videos and share them with others!

Classifying and organizing butterfly images in desktop using FastAI and Python

Source link

Unclassified butterfly images

During last 10 years, the cost of digital cameras have reduced drastically where the usage and accessibility of digital cameras had increased exponentially. Nowadays, the digital cameras are also seen incorporated in various electronic gadgets like mobile phones, wrist watches and many other devices. With increasing digital camera usage, the digital images have started accumulating in hard disks, memory cards and mobile phones leaving little time to organize these bulk data systematically. Most people do not even organize pictures taken by them. Some photographers organize only the important/ picturesque images and seldom other images of less importance. By this practice, we may lose some of the valuable memories and events. Even in the urgent requirement of images, one might have to undergo difficult time in finding the required images. Due to poor image organization, many images are at risk of getting getting lost, deleted, or even forgotten.

The main reason for poor image organization are the bulk of data, technicality and the constant battle with time.

Nowadays, many image organizer software are available in the market which helps to organize images easily. Most of the image organizers organize the images based on the EXIF details present behind the images. But, in certain specialized field like wildlife photography, organizing the images based on EXIF details are of less importance. This is one of the main limitation of the present day image organizer softwares. The most useful organizing pattern of wildlife photography is based on their actual classification/identification. Identification of a wildlife species is a tedious technical process that requires special expertise. Organizing images followed by the identification is also a laborious task that needs more time and patience.

In this article, we will present a instant and simple workflow to overcome aforementioned limitation of image organizer software and to automatically classify/identify and organize wildlife images(butterfly) using a pre-trained Convolutional Neural Network in your desktop.


Setting up the source and destination directories

Source and Destination folders of the butterfly images

We create a Source folder where the images of unclassified butterflies are copied and Destination folder where the final classified images should be moved

Setting up the Python environment

We need to install the following dependencies namely os, glob, pathlib, shutil and FastAI v1 using pip package manager.

pip install os
pip install glob
pip install shutil
pip install pathlib
pip install fastai

Importing the required dependencies

We import the following dependencies namely os, glob, pathlib, shutil and FastAI v1.

import os
import glob
from pathlib import Path
import shutil
from fastai import *
from import *

Defining the source and destination paths

We should create a source folder where the unclassified butterfly images are placed. A destination folder has to be created where the classified butterfly images are organized. The path of the source and destination folder should be specified with the code below:

source =Path(r”E:Source”) #Source folder path
destination = Path(r”E:Destination”) #Destination folder path

Loading pre-trained FastAI butterfly classifier

We load the pre-trained fastai butterfly classifier [exported using the function learn.export()] using load_learner() function available in the Fastai library.

model=Path(r”E:Sourcemodel.pkl”)   #path of butterfly classifier
learn = load_learner(model, test=ImageList.from_folder(source))

Classifying Images

We input the images from the source folder to the fastai butterfly classifier which effectively classifies the butterfly images according to the various pre-trained classes.

predictions = learn.get_preds(ds_type=DatasetType.Test)
pred=np.argmax(predictions[0], axis = 1)

Defining the predicted classes

We need to define the butterfly classes manually using the below code or by using the in-built function data.classes.

classes =[‘Common Hedge Blue (Acytolepis puspa)’ , ‘Common Pierrot (Castalius rosimon)’ , ‘Common Emigrant (Catopsilia pomona)’ , ‘Common Gull (Cepora nerissa)’ , ‘Common Nawab (Charaxes bharata)’ , ‘Chestnut Bob (Iambrix salsala)’ , ‘Plain Tiger (Danaus chrysippus)’ , ‘Common Jezebel (Delias eucharis)’ , ‘Common Grass Yellow (Eurema hecabe)’ , ‘African Marbled Skipper (Gomalia elma)’ , ‘Southern Bluebottle (Graphium teredon)’ , ‘Common Cerulean (Jamides celeno)’ , ‘Chocolate Pansy (Junonia iphita)’ , ‘Common Evening Brown (Melanitis leda)’ ,‘Common Sailor (Neptis hylas)’ , ‘Common Banded Peacock (Papilio crino)’ , ‘Lime Butterfly (Papilio demoleus)’ , ‘Slate Flash (Rapala manea)’ , ‘Apefly (Spalgis epius)’ , ‘Common Silverline (Spindasis vulcanus)’ , ‘Common Acacia Blue (Surendra quercetorum)’, ‘Red Pierrot (Talicada nyseus)’ , ‘Blue Tiger (Tirumala limniace)’ , ‘Common Three Ring (Ypthima asterope)’]
#Instead you can use
classes = data.classes

Mapping the classified data with classes

The function learn.get_preds() returns a tuple of consist of prediction percentage(tensor) and class id(integer). To make the results meaningful and understandable, we map the classified data to assigned classes using the below code:

for i in range(1):
for i in range(len(data.test_ds)):

Creating directories for different classes

We create the directories named after different classes in the model.

for name in classes:

Creating of source files and destination files

We need to create the list of source file and destination files corresponding to the correctly classified images

#Creating a list of Source File
base =source + '*.jpg'
sourcefiles = glob.glob(base)
#Creating a list of Destination File
for i in range(1):
for i in range(len(data.test_ds)):
a=os.path.join(destination, Name[i])

Moving images to classified folders

Finally, we move the images from the source file to the destination using the below code:

for f in sourcefiles:
shutil.move(f, destinationfile[i])
Source and Destination folders of the butterfly images after classifying and organizing.


We discussed a simple, instant and efficient workflow to classify the images using pre-trained Fastai butterfly classifier and to organize the butterflies images according to their original classes in the desktop. The above workflow can be used to organize any number of images using pre-trained fastai model. This workflow also overcomes one of the technical limitations of the present image organizer softwares available in the market.

I hope you found this article useful. Please let me know if you have any comments or suggestion in the comment section below.

Source link


Leave a Reply

Please Login to comment
Notify of
Translate »