Python Image Detection
Published in
1 min readOct 20, 2023
Introduction:
Explore how to perform image classification using Python and the ImageAI library. Image classification is a fundamental task in computer vision, where an algorithm assigns a label or category to an image based on its content. We will walk through a Python code example that utilizes ImageAI to classify an image and briefly explain each step.
Precondition
- Install dependencies
pip3 install cython pillow>=7.0.0 numpy>=1.18.1 opencv-python>=4.1.2 torch>=1.9.0 --extra-index-url https://download.pytorch.org/whl/cpu torchvision>=0.10.0 --extra-index-url https://download.pytorch.org/whl/cpu pytest==7.1.3 tqdm==4.64.1 scipy>=1.7.3 matplotlib>=3.4.3 mock==4.0.3
2. Install imageAI
pip3 install imageai --upgrade
Code
import warnings
warnings.filterwarnings('ignore')
from imageai.Classification import ImageClassification
import os
# Get the current working directory
exec_path = os.getcwd()
# Initialize the ImageClassification instance
prediction = ImageClassification()
# Set the model type to MobileNetV2
prediction.setModelTypeAsMobileNetV2()
# Set the path to the pre-trained model
model_path = os.path.join(exec_path, 'mobilenet_v2-b0353104.pth')
prediction.setModelPath(model_path)
# Load the pre-trained model
prediction.loadModel()
# Specify the image file to classify
image_path = os.path.join(exec_path, 'godzilla.jpg')
# Perform image classification and get the top 5 predictions
predictions, probabilities = prediction.classifyImage(image_path, result_count=5)
# Display the predictions and their probabilities
for eachPred, eachProb in zip(predictions, probabilities):
print(f'{eachPred} : {eachProb}')