Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Changing Pixel Values
Modifying pixel values is how you perform basic image editing operations. Every image transformation you will learn ultimately changes pixel values in some way.
Modifying Pixels and Regions
import cv2
import numpy as np
image = cv2.imread("photo.jpg")
h, w = image.shape[:2]
# Change a single pixel to red
image[50, 100] = [0, 0, 255] # BGR: Red
# Change a rectangular region to blue
image[100:200, 100:300] = [255, 0, 0] # BGR: Blue
# Change an entire row to white
image[50, :] = [255, 255, 255]
# Change an entire column to green
image[:, 50] = [0, 255, 0]
# Draw a filled rectangle in the centre
cx, cy = w // 2, h // 2
size = 50
image[cy-size:cy+size, cx-size:cx+size] = [0, 165, 255] # Orange
# Add noise to a region (demonstrate array operations)
region = image[300:400, 300:400]
noise = np.random.randint(-30, 30, region.shape, dtype=np.int16)
noisy_region = np.clip(region.astype(np.int16) + noise, 0, 255).astype(np.uint8)
image[300:400, 300:400] = noisy_region
cv2.imwrite("modified.jpg", image)
print("Modified image saved")Common Mistake
Warning
Pixel values must stay within the range 0–255 for uint8 images. If you add or subtract values and exceed this range, NumPy will 'wrap around' (e.g. 255 + 10 = 9, not 265). This causes unexpected colour changes. Always use np.clip(value, 0, 255).astype(np.uint8) to keep values in the valid range when doing arithmetic on pixel values.
Machine Learning follows a structured pipeline from data to deployment