Menu

Image Classification with Python

Image Classification with Python

Image classification predicts the category an image belongs to. Instead of manually defining every visual feature, a trained neural network learns useful patterns from examples.

For example, a model trained on labeled animal images may learn visual patterns associated with cats, dogs, and other animals.

Understanding CNNs

CNNs use convolutional layers to learn local patterns in images. Early layers may respond to edges and textures, while deeper layers can learn more complex structures.

Common CNN components include:

  • Convolutional layers: Learn spatial patterns using filters.
  • Activation functions: Introduce nonlinear transformations.
  • Pooling layers: Reduce spatial dimensions in some architectures.
  • Dense layers: Combine learned features to produce predictions.

Practical Example Using a Pretrained Model

A pretrained model has already learned visual features from a large image dataset. Transfer learning allows these learned features to be reused for new tasks.

Install TensorFlow:

pip install tensorflow
The following example uses MobileNetV2, a pretrained model available through TensorFlow Keras.
import tensorflow as tf
# Load a pretrained image classification model
model = tf.keras.applications.MobileNetV2(
weights="imagenet"
)
# Load an image and resize it
image = tf.keras.utils.load_img(
"sample.jpg",
target_size=(224, 224)
)
# Convert the image into a numerical array
image_array = tf.keras.utils.img_to_array(image)
# Add a batch dimension
image_array = tf.expand_dims(image_array, axis=0)
# Apply model-specific preprocessing
image_array = tf.keras.applications.mobilenet_v2.preprocess_input(
image_array
)
# Generate predictions
predictions = model.predict(image_array, verbose=0)
# Display the top predictions
results = tf.keras.applications.mobilenet_v2.decode_predictions(
predictions,
top=3
)
for _, label, score in results[0]:
print(f"{label}: {score:.2%}")

Replace sample.jpg with the path to an image file you want to classify. The first run may download pretrained model weights.

Understanding the Output

The model returns predicted ImageNet categories and associated scores. These scores are model outputs, not guarantees that a prediction is correct.

A pretrained classifier can recognize categories from its training label set. It cannot automatically identify every possible object or perform object detection merely because it can classify images.

For specialized applications, the model may need fine-tuning on relevant data.


Artificial Intelligence Tutorial

VA

Vishalini A



Learn via Video Course

Artificial Intelligence and Machine Learning Course Logo

Artificial Intelligence and Machine Learning Course

55 hrs



Get in Touch For Details