Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 54 ยท Pixels and Color

Accessing and Modifying Pixels

Read and change pixels with NumPy indexing, slice a region of interest, split and merge channels, and avoid the view-versus-copy trap. Live examples included.

Since an OpenCV image is a NumPy array, reading and changing pixels is ordinary array indexing. That is a big advantage: you can select a single pixel, a rectangle, a whole channel, or every pixel that matches a condition, all with one short expression. This lesson covers the patterns you will use constantly, and the one trap (views versus copies) that catches everyone once.

You should know the shape rules from Images Are NumPy Arrays. For deeper indexing theory, see Indexing and Slicing.

One pixel

Index with [row, col]. For a color image you get all channels of that pixel; add a third index for one channel.

Python Reading and writing single pixels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For a grayscale image the pixel is a single number: gray[10, 20]. Setting one pixel at a time inside Python loops is slow; use it for demos and tiny fixes only, and prefer slices (below) for bulk work. The Making OpenCV Fast lesson measures the difference.

You may see img.item(y, x, c) and img.itemset(...) in old tutorials. itemset was removed in NumPy 2, so use plain indexing as shown here.

Slices and regions of interest

A region of interest (ROI) is a rectangular part of the image. Slice rows first, then columns: img[y1:y2, x1:x2]. The end values are excluded, like normal Python slices.

Slice the rectangle

Pick rows y1:y2 gives the top and bottom edges.
Pick columns x1:x2 gives the left and right edges.
img[y1:y2, x1:x2] The result is the region, all channels kept.

The end index is excluded.

1 / 2
Python Paint and copy a region

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pasting works whenever the shapes match exactly. If they differ by even one pixel, NumPy raises a ValueError about shape mismatch, a useful check that your coordinates are right. A classic use is cropping a face, a license plate or a template: the crop is just a slice.

Splitting and merging channels

cv2.split(img) returns three 2D arrays (B, G, R) and cv2.merge puts them back. In NumPy you can index the last axis for the same result, which is usually faster because it does not copy:

Python
import cv2

b, g, r = cv2.split(img)           # copies; three (H, W) arrays
merged = cv2.merge([b, g, r])
Python Channels by indexing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A classic trick: zeroing a channel (as above) tints an image, and showing one channel alone as a gray image reveals where that color is strong.

The view versus copy trap

A slice does not copy pixels. It returns a view: a new array object that shares memory with the original. Changing the view changes the image. This is fast (no data is duplicated) but it surprises beginners who think they have a separate crop.

graph LR
    A["img (original memory)"] --> V["roi = img[0:2, 0:2]<br/>view, shared"]
    A --> C["roi = img[0:2, 0:2].copy()<br/>separate memory"]

A slice shares memory with the original; copy() makes an independent array.

Python Views change the original; copies do not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Plain assignment is the other source of surprise: other = img creates no copy at all; both names point to the same array. Use img.copy() whenever you want to keep the original untouched, for example before drawing boxes on a debug image. More background is in Views and Copies.

Masking by assignment

A boolean mask is an array of True and False with the same height and width as the image. Using it as an index selects exactly the pixels where the mask is True, and assigning through it changes only those pixels. This is how you find "all dark pixels" or "all pixels brighter than 200" without a loop.

Python Brighten only the dark pixels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With a 2D mask on a color image, all three channels of each selected pixel are set together, so the value you assign must be a 3-tuple (or broadcastable to the right shape). Later chapters use OpenCV's inRange to build such masks from color ranges; the mechanics are identical to the comparison above. See also Boolean Masks.

Pixel assignment with uint8 values wraps around instead of clipping when you do arithmetic first (for example 200 + 100 becomes 44). Assigning a plain constant is safe, but arithmetic on pixels needs care; the next lessons cover it in depth.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which expression gives the region from row 20 up to (not including) row 60 and column 10 up to (not including) column 50?

    Rows (y) come first, then columns (x): img[y1:y2, x1:x2].
  2. 2. You write roi = img[0:100, 0:100] and then roi[:] = 0. What happens to img?

    A slice is a view that shares memory with img, so editing it edits img.
  3. 3. How do you make an independent copy of a region?

    .copy() allocates new memory so later edits do not touch the original.
  4. 4. What does img[..., 1] return for a BGR image?

    The ellipsis keeps all earlier axes, and index 1 on the last axis is green in BGR order.
  5. 5. Which is the right way to set every pixel brighter than 200 to 255 without a loop?

    A boolean mask used as an index selects those pixels, and assignment changes only them.

Summary

  • Index pixels with img[row, col]; add a third index for one channel; use slices img[y1:y2, x1:x2] for regions.
  • Split channels with cv2.split or by indexing img[..., c]; merge with cv2.merge or np.dstack.
  • Slices are views: edits change the original; use .copy() for independent data.
  • Boolean masks select and change many pixels at once without loops.

Next: Data Types, Ranges and Saturation.