Introduction:
In this tutorial, we will build an image recognition application using Python and deep learning. Image recognition is a fascinating field that enables computers to identify and classify objects or patterns within images. We will utilize Python libraries such as TensorFlow and Keras to create a convolutional neural network (CNN) model, train it on a dataset of labeled images, and then use the trained model to classify new images. By the end of this tutorial, you will have a working image recognition application that can accurately identify objects in images.
Prerequisites:
1. Basic understanding of Python programming.
2. Familiarity with deep learning concepts and neural networks.
Step 1: Setting Up the Environment
Create a new directory for your project and navigate to it in a terminal or command prompt. Set up a virtual environment:
```
$ python -m venv image-recognition-env
```
Activate the virtual environment:
- On Windows:
```
$ image-recognition-env\Scripts\activate
```
- On macOS/Linux:
```
$ source image-recognition-env/bin/activate
```
Step 2: Installing Dependencies
Inside the activated virtual environment, install the necessary libraries:
```
$ pip install tensorflow keras
```
Step 3: Gathering and Preparing the Dataset
Find or create a dataset of labeled images suitable for your image recognition task. Ensure that you have separate folders for each class of images.
Step 4: Writing the Code
Create a new Python file in your project directory, e.g., `image_recognition.py`. Open the file in a text editor or IDE and follow along with the code below:
```python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Define the CNN model architecture
model = keras.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 3)),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10)
])
# Compile the model
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# Load and preprocess the dataset
dataset = keras.preprocessing.image_dataset_from_directory(
'path/to/dataset',
batch_size=32,
image_size=(64, 64)
)
# Train the model
model.fit(dataset, epochs=10)
# Classify new images
class_names = dataset.class_names
# Load and preprocess the new image
new_image = keras.preprocessing.image.load_img('path/to/new/image.jpg', target_size=(64, 64))
new_image_array = keras.preprocessing.image.img_to_array(new_image)
new_image_array = tf.expand_dims(new_image_array, 0)
# Make predictions
predictions = model.predict(new_image_array)
predicted_class = class_names[predictions[0].argmax()]
# Display the result
print(f"Predicted class: {predicted_class}")
```
Step 5: Understanding the Code
- We import TensorFlow and Keras, the libraries for building and training deep learning models.
- We define the architecture of the CNN model using Keras' Sequential API.
- The model is compiled with an optimizer, loss function, and evaluation metrics.
- We load and preprocess the dataset using Keras' `image_dataset_from_directory` function.
- The model is trained on the dataset using the `fit` method.
- We define the class names based on the dataset folders.
- A new image is loaded, preprocessed, and classified using the trained model.
- The predicted class is displayed.
Step 6: Running
the Image Recognition Application
Save the `image_recognition.py` file and execute it from the command line:
```
$ python image_recognition.py
```
The image recognition application will train the model on the dataset, and then classify a new image, displaying the predicted class.
Conclusion:
In this tutorial, we built an image recognition application using Python and deep learning techniques. Image recognition has numerous applications, from object detection to facial recognition. You can further enhance the application by exploring more advanced models, utilizing pre-trained models, or working with larger datasets. Start exploring the fascinating field of image recognition with your own application!
Support My Work with a Cup of Chai ! ☕
If you are located in India, I kindly request your support through a small contribution.
Please note that the UPI payment method is only available within India.
UPI ID :
haneenthecreate@postbank
If you are not located in India, you can still show your appreciation by sending a thank you or an Amazon gift card to the following email address:
websitehaneen@gmail.com
Wishing you a wonderful day!
HaneentheCREATE is now available in the Nas community (Nas Daily)! Become a member and join us