Texture & Object Detection
STEP 1 · OVERVIEW

Texture Extraction & Pedestrian Detection

In this codelab we will create the two practical programs from your syllabus: texture extraction from an image and object detection by recognizing pedestrians.

By the end: You will be able to load images with OpenCV, extract simple GLCM texture features, detect pedestrians with HOG, draw bounding boxes, and explain every important line of both programs.
Program 7

Implement texture extraction of a given image.

Program 8

Implement object detection, for example recognizing pedestrians.

Program 7
Image → Grayscale → GLCM → Texture numbers

Program 8
Image → HOG pedestrian detector → Bounding boxes → Detected people
Important:

This codelab focuses on the practical. We will learn only the amount of theory needed to understand and write the programs.

STEP 2 · SETUP

Install the Required Libraries

We will use OpenCV for image processing and scikit-image for the GLCM texture calculation.

pip install opencv-python scikit-image
Library Why we need it
opencv-python Reads images, displays images, resizes images, and draws rectangles.
scikit-image Provides graycomatrix() and graycoprops() for texture extraction.
Files to keep ready:

Put one texture image such as texture.jpg and one pedestrian image such as pedestrians.jpg in the same folder as your Python program.

STEP 3 · PROGRAM 7

What Does Texture Extraction Mean?

Texture tells us whether an area looks smooth, rough, repetitive, irregular, or strongly patterned.

Image pixels
↓
Look at neighboring gray values
↓
Build a GLCM
↓
Calculate texture features
Contrast

How strongly neighboring pixels differ.

Homogeneity

How similar neighboring pixels are.

Energy

How uniform or orderly the texture is.

Correlation

How strongly neighboring gray levels are related.

Easy memory:

We are converting the visual texture of an image into a few numerical values.

STEP 4 · LOAD THE IMAGE

Read the Image in Grayscale

A GLCM works with gray-level values, so the easiest approach is to load the image directly as grayscale.

import cv2
from skimage.feature import graycomatrix, graycoprops

image = cv2.imread("texture.jpg", cv2.IMREAD_GRAYSCALE)
Line Very simple meaning
import cv2 Loads OpenCV so we can work with images.
from skimage.feature ... Imports the two functions we need for GLCM and texture features.
cv2.imread(...) Reads the image from the computer.
cv2.IMREAD_GRAYSCALE Loads it as one-channel grayscale instead of BGR color.
CHECKPOINT

If image becomes None, the file name or path is wrong.

STEP 5 · BUILD THE MATRIX

Create the Gray-Level Co-occurrence Matrix

The GLCM counts how often one grayscale value appears next to another grayscale value.

glcm = graycomatrix(
    image,
    distances=[1],
    angles=[0],
    levels=256,
    symmetric=True,
    normed=True
)
Part Meaning
image The grayscale image whose texture we want to study.
distances=[1] Compare each pixel with a neighbor one pixel away.
angles=[0] Look at the neighbor to the right.
levels=256 Grayscale has values from 0 to 255, so there are 256 possible levels.
symmetric=True Treat A-next-to-B and B-next-to-A as the same kind of relationship.
normed=True Convert raw counts into normalized values so the matrix is easier to use.
You do not need to print the whole GLCM.

It can be very large. Our goal is to extract useful numbers from it.

STEP 6 · EXTRACT FEATURES

Calculate the Texture Values

graycoprops() reads the GLCM and calculates useful texture properties.

contrast = graycoprops(glcm, "contrast")[0, 0]
homogeneity = graycoprops(glcm, "homogeneity")[0, 0]
energy = graycoprops(glcm, "energy")[0, 0]
correlation = graycoprops(glcm, "correlation")[0, 0]

print("Contrast:", contrast)
print("Homogeneity:", homogeneity)
print("Energy:", energy)
print("Correlation:", correlation)
Line Meaning
graycoprops(glcm, "contrast") Calculates how different neighboring gray values are.
[0, 0] We used one distance and one angle, so we take the first result.
"homogeneity" Measures neighbor similarity.
"energy" Measures texture uniformity/order.
"correlation" Measures the relationship between neighboring gray levels.
print(...) Shows the calculated values in the terminal.

Which function calculates contrast, homogeneity, energy, and correlation?

STEP 7 · COMPLETE PROGRAM

Program 7: Texture Extraction

Here is the complete practical in one file.

import cv2
from skimage.feature import graycomatrix, graycoprops

image = cv2.imread("texture.jpg", cv2.IMREAD_GRAYSCALE)

if image is None:
    print("Image not found")
    exit()

glcm = graycomatrix(
    image,
    distances=[1],
    angles=[0],
    levels=256,
    symmetric=True,
    normed=True
)

contrast = graycoprops(glcm, "contrast")[0, 0]
homogeneity = graycoprops(glcm, "homogeneity")[0, 0]
energy = graycoprops(glcm, "energy")[0, 0]
correlation = graycoprops(glcm, "correlation")[0, 0]

print("Contrast:", contrast)
print("Homogeneity:", homogeneity)
print("Energy:", energy)
print("Correlation:", correlation)

cv2.imshow("Texture Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
What happens when you run it?

The image opens in a window, and the terminal displays four numerical texture features.

Try this

  1. Run the program using an image of a smooth wall.
  2. Run it again using grass, fabric, or gravel.
  3. Compare the feature values.
STEP 8 · TRACE THE PROGRAM

What Happens in What Order?

Before moving to object detection, make sure the flow of Program 7 is clear.

1. Import libraries
↓
2. Read grayscale image
↓
3. Check whether image loaded
↓
4. Create GLCM
↓
5. Calculate texture features
↓
6. Print features
↓
7. Display image
Why grayscale?
GLCM studies gray-level relationships, so a grayscale image gives one intensity value per pixel.
Why distances=[1]?
We compare each pixel with an immediately neighboring pixel.
Why [0, 0] after graycoprops()?
Because our GLCM contains one distance and one angle, so the first row and first column contain the one value we need.
STEP 9 · PROGRAM 8

What Is Object Detection?

Object detection finds an object and also tells us where that object appears in the image.

Classification

“There is a pedestrian in this image.”

Detection

“There is a pedestrian here,” and we draw a box around the person.

Input image
↓
HOG features
↓
Pedestrian detector
↓
Coordinates of detected people
↓
Draw rectangles
For this practical:

We will use OpenCV's built-in HOG pedestrian detector. We do not need to train our own model.

STEP 10 · LOAD INPUT

Read the Pedestrian Image

This time we keep the image in color because we want to display the detected people with colored boxes.

import cv2

image = cv2.imread("pedestrians.jpg")

if image is None:
    print("Image not found")
    exit()
Line Meaning
import cv2 Imports OpenCV.
cv2.imread(...) Reads the image in OpenCV's normal BGR color format.
if image is None Checks whether loading failed.
exit() Stops the program if there is no valid image to process.
STEP 11 · CREATE DETECTOR

Create the HOG Pedestrian Detector

HOG stands for Histogram of Oriented Gradients. It describes edge and shape patterns, which are useful for recognizing the shape of a person.

hog = cv2.HOGDescriptor()
hog.setSVMDetector(
    cv2.HOGDescriptor_getDefaultPeopleDetector()
)
Line Very simple meaning
cv2.HOGDescriptor() Creates an object that can calculate and use HOG features.
getDefaultPeopleDetector() Gets OpenCV's already-trained detector for human pedestrians.
setSVMDetector(...) Attaches that trained people detector to our HOG object.
Easy memory:

HOGDescriptor() creates the detector machinery. getDefaultPeopleDetector() gives it knowledge of what a pedestrian looks like.

STEP 12 · RUN DETECTION

Find People with detectMultiScale()

A pedestrian can appear at different sizes in an image, so OpenCV scans the image at multiple scales.

boxes, weights = hog.detectMultiScale(
    image,
    winStride=(8, 8),
    padding=(8, 8),
    scale=1.05
)
Part Meaning
detectMultiScale() Searches the image for pedestrians at different sizes.
image The image to search.
winStride=(8, 8) Moves the detection window across the image in small steps.
padding=(8, 8) Adds a small extra area around scanning windows.
scale=1.05 Checks the image at gradually changing sizes.
boxes Contains the position and size of every detected person.
weights Contains confidence-like scores returned by the detector.
IMPORTANT

Each item in boxes contains four numbers: x, y, w, h.

STEP 13 · SHOW RESULTS

Draw a Rectangle Around Every Person

The detector gives us coordinates. Now we turn those coordinates into visible bounding boxes.

for (x, y, w, h) in boxes:
    cv2.rectangle(
        image,
        (x, y),
        (x + w, y + h),
        (0, 255, 0),
        2
    )
Part Meaning
for ... in boxes Repeat once for every detected pedestrian.
x, y Top-left position of the detected box.
w, h Width and height of the detected box.
(x, y) Top-left corner of the rectangle.
(x + w, y + h) Bottom-right corner.
(0, 255, 0) Green color in OpenCV BGR format.
2 Rectangle border thickness.

What does w represent in (x, y, w, h)?

STEP 14 · COMPLETE PROGRAM

Program 8: Pedestrian Detection

Now combine every step into one working OpenCV program.

import cv2

image = cv2.imread("pedestrians.jpg")

if image is None:
    print("Image not found")
    exit()

hog = cv2.HOGDescriptor()
hog.setSVMDetector(
    cv2.HOGDescriptor_getDefaultPeopleDetector()
)

boxes, weights = hog.detectMultiScale(
    image,
    winStride=(8, 8),
    padding=(8, 8),
    scale=1.05
)

for (x, y, w, h) in boxes:
    cv2.rectangle(
        image,
        (x, y),
        (x + w, y + h),
        (0, 255, 0),
        2
    )

print("Pedestrians detected:", len(boxes))

cv2.imshow("Pedestrian Detection", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Expected result:

The output window shows the original image with green rectangles around detected pedestrians. The terminal prints how many detections were returned.

Try these changes

  1. Change the rectangle color.
  2. Change thickness from 2 to 4.
  3. Try an image with multiple people.
  4. Try an image with no people and observe len(boxes).
STEP 15 · TRACE THE PROGRAM

What Happens During Pedestrian Detection?

Follow the program from top to bottom.

1. Import OpenCV
↓
2. Read image
↓
3. Create HOG descriptor
↓
4. Load default pedestrian detector
↓
5. Scan image with detectMultiScale()
↓
6. Get x, y, w, h boxes
↓
7. Draw rectangles
↓
8. Display result
What is HOG?
Histogram of Oriented Gradients. It describes the direction of edges and shapes inside image regions.
Do we train the detector ourselves?
No. OpenCV gives us a built-in default pedestrian detector.
Why detectMultiScale()?
Because a person may appear small, medium, or large depending on their distance from the camera.
STEP 16 · CONNECT THE IDEAS

Texture Extraction vs Object Detection

Both programs extract useful information from images, but the outputs are different.

Point Texture Extraction Pedestrian Detection
Input Grayscale image Color image
Main technique GLCM HOG + pedestrian detector
Output Numerical texture features Bounding boxes around people
Main library OpenCV + scikit-image OpenCV
Example use Compare smooth and rough surfaces Recognize pedestrians
STEP 17 · QUICK REVISION

Practical Viva Questions

Use these to revise before lab evaluation or viva.

1. What is texture extraction?
It converts the visual texture of an image into numerical features that describe properties such as contrast and homogeneity.
2. What is GLCM?
Gray-Level Co-occurrence Matrix. It describes how often different grayscale values occur next to each other.
3. Why do we load the texture image as grayscale?
Because GLCM works with gray-level intensity relationships.
4. What does graycoprops() do?
It extracts properties such as contrast, homogeneity, energy, and correlation from a GLCM.
5. What is object detection?
It finds an object and also locates it in the image.
6. What is HOG?
Histogram of Oriented Gradients, a feature descriptor based on edge directions.
7. What does detectMultiScale() do?
It scans an image at multiple sizes and returns bounding boxes for detected objects.
8. What are x, y, w, and h?
x and y are the top-left coordinates; w and h are the width and height of the detected rectangle.
9. What does cv2.rectangle() do?
It draws a rectangle on an image.

Completion checklist

  • I can load a grayscale image.
  • I can create a GLCM.
  • I can extract contrast, homogeneity, energy, and correlation.
  • I can explain every line of Program 7.
  • I can create a HOG descriptor.
  • I can use OpenCV's default people detector.
  • I can use detectMultiScale().
  • I understand x, y, w, and h.
  • I can draw bounding boxes.
  • I can explain every line of Program 8.

Codelab complete! 🎉

You can now implement both syllabus practicals: texture extraction and pedestrian object detection.