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.
Implement texture extraction of a given image.
Implement object detection, for example recognizing pedestrians.
Image → Grayscale → GLCM → Texture numbers
Program 8
Image → HOG pedestrian detector → Bounding boxes → Detected people
This codelab focuses on the practical. We will learn only the amount of theory needed to understand and write the programs.
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. |
Put one texture image such as texture.jpg and one pedestrian image such as
pedestrians.jpg in the same folder as your Python program.
What Does Texture Extraction Mean?
Texture tells us whether an area looks smooth, rough, repetitive, irregular, or strongly patterned.
↓
Look at neighboring gray values
↓
Build a GLCM
↓
Calculate texture features
How strongly neighboring pixels differ.
How similar neighboring pixels are.
How uniform or orderly the texture is.
How strongly neighboring gray levels are related.
We are converting the visual texture of an image into a few numerical values.
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. |
If image becomes None, the file name or path is wrong.
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. |
It can be very large. Our goal is to extract useful numbers from it.
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?
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()
The image opens in a window, and the terminal displays four numerical texture features.
Try this
- Run the program using an image of a smooth wall.
- Run it again using grass, fabric, or gravel.
- Compare the feature values.
What Happens in What Order?
Before moving to object detection, make sure the flow of Program 7 is clear.
↓
2. Read grayscale image
↓
3. Check whether image loaded
↓
4. Create GLCM
↓
5. Calculate texture features
↓
6. Print features
↓
7. Display image
distances=[1]?[0, 0] after graycoprops()?What Is Object Detection?
Object detection finds an object and also tells us where that object appears in the image.
“There is a pedestrian in this image.”
“There is a pedestrian here,” and we draw a box around the person.
↓
HOG features
↓
Pedestrian detector
↓
Coordinates of detected people
↓
Draw rectangles
We will use OpenCV's built-in HOG pedestrian detector. We do not need to train our own model.
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. |
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. |
HOGDescriptor() creates the detector machinery.
getDefaultPeopleDetector() gives it knowledge of what a pedestrian looks like.
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. |
Each item in boxes contains four numbers: x, y, w, h.
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)?
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()
The output window shows the original image with green rectangles around detected pedestrians. The terminal prints how many detections were returned.
Try these changes
- Change the rectangle color.
- Change thickness from
2to4. - Try an image with multiple people.
- Try an image with no people and observe
len(boxes).
What Happens During Pedestrian Detection?
Follow the program from top to bottom.
↓
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
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 |
Practical Viva Questions
Use these to revise before lab evaluation or viva.
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.