Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 54 ยท Getting Started

Images Are NumPy Arrays

In Python an OpenCV image is a NumPy array. Learn pixels, shape (height, width, channels), uint8 values and row-column order by building images from scratch.

Here is the single most useful fact in OpenCV for Python: an image is a NumPy array. There is no special image class. cv2.imread returns an ndarray, every cv2 function takes and returns arrays, and anything you can do with NumPy (slicing, math, comparisons) works on pictures directly.

This lesson explains how an array represents a picture: what the shape means, why values are usually uint8, and why rows come before columns. If arrays are new to you, read Your First Arrays first; this lesson builds on it.

Pixels, rows and columns

A pixel is one dot of the image. A grayscale image stores one number per pixel, so it is a 2D array. A color image stores three numbers per pixel, so it is a 3D array.

Reading an image's shape

Height The number of rows, axis 0.
Width The number of columns, axis 1.
Channels Values per pixel, axis 2.

A color photo of 480 by 640 pixels has shape (480, 640, 3).

1 / 2

The array's shape lists axes from outermost to innermost, so the first number is the height (how many rows) and the second is the width (how many columns). This is the opposite of the "width by height" you see in screen resolutions like 1920x1080, and it is the source of countless bugs. We will use "H, W" consistently.

Python Shapes of gray and color images

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.

Notice shape[:2]. Slicing the first two entries gives (height, width) for both gray and color images, which is why you see it all over OpenCV code.

Why uint8

Most images use the type uint8: an unsigned 8-bit integer from 0 to 255. Zero is black (no light) and 255 is full brightness. One byte per channel keeps files and memory small, and 256 levels per channel give about 16.7 million colors, which is plenty for photos.

A 640 by 480 color image therefore needs 640 * 480 * 3 = 921,600 bytes, under a megabyte.

Python dtype, itemsize and memory

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.

Some operations use float32 instead (values often scaled to 0 to 1), which takes four times the memory. Data Types, Ranges and Saturation covers the pitfalls of switching between them.

Row, column versus x, y

To read one pixel you index img[row, col], which is img[y, x] in drawing terms: the vertical position first. Many OpenCV drawing and geometry functions, however, take points as (x, y). Keep the two conventions straight and you avoid half the beginner errors.

graph LR
    A["Indexing: img[y, x]<br/>row first"] --> C["Same pixel"]
    B["Points in cv2 calls: (x, y)<br/>column first"] --> C

Array indexing goes row-then-column; most cv2 point arguments go x-then-y.

Python Row first when 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.

If you swapped the two numbers here you would get an IndexError, because axis 0 only has 3 rows. On a square image the swap would not even raise an error: it would silently touch the wrong pixel.

Building an image from scratch

You do not need a file to practice. Three functions create most test images: np.zeros (black), np.full (a solid value) and np.arange combined with broadcasting (gradients).

For the color case, remember that OpenCV orders channels B, G, R (blue first). We discuss that in Color Spaces; for now just keep it in mind when you set a color value.

Python Gradient, solid color and a stripe

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.

Slicing canvas[:, 3:5] means "all rows, columns 3 and 4". Because the stripe is created by assigning into a slice, no loop is needed. This is the style you should aim for: whole-array operations instead of pixel-by-pixel loops.

What the real cv2 code looks like

Everything above works identically on an image loaded by OpenCV. This block is read-only (it needs the real library and a file):

Python
import cv2

img = cv2.imread("photo.jpg")      # a NumPy array, or None if the path is wrong
print(type(img))                    # <class 'numpy.ndarray'>
print(img.shape, img.dtype)         # e.g. (480, 640, 3) uint8

h, w, channels = img.shape
print(img[100, 200])                # the B, G, R values of one pixel

The crucial point: nothing in the array says "this is a JPEG" or "this is a photo". It is just numbers, and the meaning (BGR order, 0 to 255) is a convention you must remember.

Some images carry a fourth channel, alpha (opacity), giving shape (H, W, 4). A plain cv2.imread(path) discards alpha and returns 3 channels; you must ask for it explicitly, as the next lesson shows.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the shape of a color image that is 480 pixels tall and 640 pixels wide?

    Shape is (height, width, channels). Height is the number of rows, so 480 comes first.
  2. 2. Which dtype do most OpenCV images use?

    uint8 holds 0 to 255 per channel, which keeps images small and covers normal brightness levels.
  3. 3. To change the pixel in row 10, column 20, you write:

    NumPy indexes rows first: img[row, col], which is img[y, x].
  4. 4. How many bytes does a 100 x 100 uint8 color image occupy?

    100 * 100 pixels times 3 channels times 1 byte equals 30,000 bytes.
  5. 5. What does an image loaded by cv2.imread have to do with NumPy?

    OpenCV for Python uses ndarray for all images, so every NumPy tool works on them.

Summary

  • An OpenCV image in Python is a NumPy ndarray: shape (H, W) for gray, (H, W, 3) for color.
  • Typical dtype is uint8 with values 0 to 255; memory is height * width * channels bytes.
  • Index with img[row, col] ([y, x]); many cv2 functions take points as (x, y).
  • Create test images with np.zeros, np.full and slicing assignments instead of loops.

Next, learn how to get real files into and out of arrays: Reading, Showing and Saving Images.