Syllabus Lesson 11 of 246 · Module 1: Python for this course
Module 1: Python for this course

Cutting pieces out of an image

Why it matters Images in this course are arrays. Cutting out a row, a column or a small window is how you will build convolutions later.

For a 2D array img, img[r, c] is one pixel, img[r] is row r, img[:, c] is column c, and img[r0:r1, c0:c1] is the window from rows r0 up to (not including) r1 and columns c0 up to c1.

Tiny numbers

img = np.arange(16).reshape(4, 4)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]
#  [12 13 14 15]]
img[1, 2]      # 6
img[:, 0]      # [0 4 8 12]
img[0:2, 0:2]  # [[0 1] [4 5]]
img[::2, ::2]  # every other row and column: [[0 2] [8 10]]

Recap Rows first, then columns. A slice stops before its end number.

Words and symbols in this lesson
array
a NumPy block of numbers, all the same type, that does maths on every item at once
shape
the size of an array along each direction, for example (32, 64) is 32 rows of 64
Your turn

Write window(img, r, c, size) that returns the size by size square whose top-left pixel is at row r, column c. And write downsample(img) that keeps every other row and every other column, starting at 0. No loops needed.

Spotted a problem in this lesson? Report it · Ask about this lesson

This exercise opens soon

Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.