Computer Vision • Python • Machine Learning

How to Start Making Picture Classification Programs

A zero-level lesson for beginners: folders, labels, image reading, image-to-number conversion, simple classifiers, complete cat/dog/mango prediction code, and the path towards Convolutional Neural Networks.

1. Start Very Small

Do picture classification in levels. Do not start with a big Artificial Intelligence project immediately. First learn how an image becomes data, how a label is attached, and how a model learns from examples.

Picture Resize Convert to Numbers Train Model Predict Class
Best first project: Start with only two classes: apple and banana. Take around 20 images of each. After that works, add more classes.

2. Level 1: Classify Pictures by Folder Name

The simplest dataset is made using folders. Each folder name becomes a class name.

pictures/
    cat/
        cat1.jpg
        cat2.jpg
    dog/
        dog1.jpg
        dog2.jpg
    mango/
        mango1.jpg
        mango2.jpg
Image Path Class Label
pictures/cat/cat1.jpg cat
pictures/dog/dog1.jpg dog
pictures/mango/mango1.jpg mango

3. Level 2: Read and Display an Image

Install these Python libraries first:

pip install pillow matplotlib

Python program:

from PIL import Image
import matplotlib.pyplot as plt

img = Image.open("pictures/cat/cat1.jpg")

print("Image size:", img.size)
print("Image mode:", img.mode)

plt.imshow(img)
plt.axis("off")
plt.show()
This teaches the first important flow: image file → Python image object → display on screen.

4. Level 3: Convert Image into Numbers

Computers do not understand pictures directly. They understand numbers. An image is finally stored as pixel values.

from PIL import Image
import numpy as np

img = Image.open("pictures/cat/cat1.jpg")
img = img.resize((64, 64))

arr = np.array(img)

print(arr.shape)
print(arr)

Output shape may be:

(64, 64, 3)
64 rows Height of the image after resizing.
64 columns Width of the image after resizing.
3 color channels Red, Green, and Blue values.

5. Level 4: Make a Simple Dataset Loader

Now read all images from all class folders. Store image data in X and labels in y.

from PIL import Image
import numpy as np
import os

X = []
y = []

base_folder = "pictures"
classes = ["cat", "dog", "mango"]

for label_number, class_name in enumerate(classes):
    folder_path = os.path.join(base_folder, class_name)

    for file_name in os.listdir(folder_path):
        image_path = os.path.join(folder_path, file_name)

        img = Image.open(image_path).convert("RGB")
        img = img.resize((64, 64))

        arr = np.array(img)

        X.append(arr)
        y.append(label_number)

X = np.array(X)
y = np.array(y)

print("Images shape:", X.shape)
print("Labels shape:", y.shape)
print("Labels:", y)
Class Label Number
cat 0
dog 1
mango 2

6. Level 5: First Simple Classifier Using Average Color

Before Deep Learning, make a very simple classifier. This program checks the average Red, Green, and Blue value of each image.

from PIL import Image
import numpy as np
import os
from sklearn.neighbors import KNeighborsClassifier

X = []
y = []

base_folder = "pictures"
classes = ["cat", "dog", "mango"]

for label_number, class_name in enumerate(classes):
    folder_path = os.path.join(base_folder, class_name)

    for file_name in os.listdir(folder_path):
        image_path = os.path.join(folder_path, file_name)

        img = Image.open(image_path).convert("RGB")
        img = img.resize((64, 64))

        arr = np.array(img)
        average_color = arr.mean(axis=(0, 1))

        X.append(average_color)
        y.append(label_number)

X = np.array(X)
y = np.array(y)

model = KNeighborsClassifier(n_neighbors=3)
model.fit(X, y)

test_img = Image.open("test.jpg").convert("RGB")
test_img = test_img.resize((64, 64))
test_arr = np.array(test_img)

test_average_color = test_arr.mean(axis=(0, 1)).reshape(1, -1)

prediction = model.predict(test_average_color)

print("Predicted class:", classes[prediction[0]])
Important: This is not a powerful classifier. It can fail easily. But it is a perfect starting point because it teaches the full pipeline.

7. Complete Cat / Dog / Mango Classification and Prediction Code

This is a complete beginner-friendly Python program. It reads images from cat, dog, and mango folders, trains a simple classifier, checks its accuracy, and then predicts the class of a new image.

Folder structure required: Keep your images in this format before running the program.
picture_classification_project/
    main.py
    test.jpg
    pictures/
        cat/
            cat1.jpg
            cat2.jpg
            cat3.jpg
        dog/
            dog1.jpg
            dog2.jpg
            dog3.jpg
        mango/
            mango1.jpg
            mango2.jpg
            mango3.jpg

Install the required libraries:

pip install pillow numpy scikit-learn matplotlib

Complete Python Program

from PIL import Image
import numpy as np
import os
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt


# --------------------------------------------------
# 1. Basic settings
# --------------------------------------------------

base_folder = "pictures"

classes = ["cat", "dog", "mango"]

image_width = 64
image_height = 64


# --------------------------------------------------
# 2. Function to convert one image into useful numbers
# --------------------------------------------------

def image_to_features(image_path):
    """
    This function takes an image path,
    opens the image,
    converts it to RGB,
    resizes it,
    converts it into a NumPy array,
    and returns simple features.

    Here we use average Red, Green, and Blue values.
    """

    img = Image.open(image_path).convert("RGB")
    img = img.resize((image_width, image_height))

    arr = np.array(img)

    average_red = arr[:, :, 0].mean()
    average_green = arr[:, :, 1].mean()
    average_blue = arr[:, :, 2].mean()

    features = [average_red, average_green, average_blue]

    return features


# --------------------------------------------------
# 3. Read all training images
# --------------------------------------------------

X = []
y = []

for label_number, class_name in enumerate(classes):
    folder_path = os.path.join(base_folder, class_name)

    if not os.path.exists(folder_path):
        print("Folder not found:", folder_path)
        continue

    for file_name in os.listdir(folder_path):
        file_name_lower = file_name.lower()

        if not (
            file_name_lower.endswith(".jpg")
            or file_name_lower.endswith(".jpeg")
            or file_name_lower.endswith(".png")
        ):
            continue

        image_path = os.path.join(folder_path, file_name)

        try:
            features = image_to_features(image_path)

            X.append(features)
            y.append(label_number)

            print("Loaded:", image_path, "Label:", class_name)

        except Exception as e:
            print("Could not read image:", image_path)
            print("Error:", e)


X = np.array(X)
y = np.array(y)


# --------------------------------------------------
# 4. Check whether enough images are available
# --------------------------------------------------

print()
print("Total images loaded:", len(X))
print("Feature shape:", X.shape)
print("Labels shape:", y.shape)

if len(X) == 0:
    print("No images found.")
    print("Please add images inside cat, dog, and mango folders.")
    exit()

if len(set(y)) < 2:
    print("At least two classes are needed for training.")
    exit()


# --------------------------------------------------
# 5. Split data into training and testing parts
# --------------------------------------------------

# If every class has at least 2 images, we can use stratify.
# Stratify tries to keep the same class balance in train and test data.

can_use_stratify = True

for class_number in set(y):
    if list(y).count(class_number) < 2:
        can_use_stratify = False

if can_use_stratify:
    X_train, X_test, y_train, y_test = train_test_split(
        X,
        y,
        test_size=0.25,
        random_state=42,
        stratify=y
    )
else:
    X_train, X_test, y_train, y_test = train_test_split(
        X,
        y,
        test_size=0.25,
        random_state=42
    )


# --------------------------------------------------
# 6. Train the classifier
# --------------------------------------------------

# n_neighbors should not be bigger than the number of training images.
# So we choose 3 when possible, otherwise choose 1.

if len(X_train) >= 3:
    neighbors = 3
else:
    neighbors = 1

model = KNeighborsClassifier(n_neighbors=neighbors)

model.fit(X_train, y_train)

print()
print("Training completed successfully.")
print("KNN neighbors used:", neighbors)


# --------------------------------------------------
# 7. Test the model on test data
# --------------------------------------------------

y_pred = model.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)

print("Model accuracy:", accuracy)

print()
print("Testing details:")

for i in range(len(X_test)):
    actual_class = classes[y_test[i]]
    predicted_class = classes[y_pred[i]]

    print("Actual:", actual_class, "Predicted:", predicted_class)


# --------------------------------------------------
# 8. Predict a new image
# --------------------------------------------------

test_image_path = "test.jpg"

if not os.path.exists(test_image_path):
    print()
    print("Prediction image not found.")
    print("Please keep a file named test.jpg in the project folder.")

else:
    test_features = image_to_features(test_image_path)

    test_features = np.array(test_features).reshape(1, -1)

    prediction = model.predict(test_features)

    predicted_class = classes[prediction[0]]

    print()
    print("New image:", test_image_path)
    print("Predicted class:", predicted_class)

    img = Image.open(test_image_path)

    plt.imshow(img)
    plt.axis("off")
    plt.title("Predicted class: " + predicted_class)
    plt.show()

How the Program Works

Part Meaning
classes = ["cat", "dog", "mango"] These are the three picture categories.
image_to_features() Converts one picture into useful numbers.
X Stores image features.
y Stores correct answers or labels.
train_test_split() Divides the data into training data and testing data.
KNeighborsClassifier The Machine Learning model used for classification.
model.fit() Trains the model.
model.predict() Predicts the class of a new picture.
accuracy_score() Checks how many test predictions were correct.

Meaning of the Main Variables

Variable Use
base_folder The main folder where class folders are kept.
classes The names of all categories.
image_width and image_height The size to which every image is resized.
features The average red, green, and blue values of an image.
prediction The class number predicted by the model.
predicted_class The final class name, such as cat, dog, or mango.
Important: This program uses average color only. It is good for learning the pipeline, but it may not classify cats and dogs accurately because cats and dogs can have similar colors. For better accuracy, use a Convolutional Neural Network later.

8. Level 6: Then Move to CNN

After the above is clear, move to a Convolutional Neural Network, also called CNN. CNNs are designed for image data.

Edges Shapes Parts Full Object

Install TensorFlow later when you are ready for CNN:

pip install tensorflow

Then build this larger flow:

Image folder → training data → CNN model → prediction
Why CNN is better: A CNN does not depend only on average color. It can learn edges, shapes, patterns, eyes, ears, fruit outlines, textures, and other visual features.

9. Practice Task

Your First Assignment

Create this folder structure:

pictures/
    apple/
    banana/

Put 20 apple images and 20 banana images. Then run the image reading program, the image-to-number program, and finally the average color classifier.

Your Second Assignment

Create this folder structure:

pictures/
    cat/
    dog/
    mango/

Put at least 10 images in each folder. Then keep one new image as test.jpg and run the complete classification code.

Step 1 Read one image and display it.
Step 2 Resize the image to 64 × 64.
Step 3 Convert the image into a NumPy array.
Step 4 Train the first simple classifier.
Step 5 Predict the class of a new image.
Step 6 Improve the project later using CNN.