Runoob Tutorial ArchiveEnglish

An image is a matrix

An image is a matrix

A grayscale image is essentially a two-dimensional NumPy array. When you transpose, flip, crop, or convolve a matrix, the image changes accordingly.

After completing this case study, you will understand: the foundation of image processing is linear algebra, and a matrix is a table of numbers.


Introduction to life

**Pixel squares of a photo

Zooming in on a photo from your phone, and zooming in again and again—until you can see individual small squares. Each square has only one color value: 0 represents pure black, 255 represents pure white, and the numbers in between represent different shades of gray.

The entire photo is a rectangular array formed by these small squares—mathematicians call it a "matrix".


Intuitive understanding

A matrix is not some profound concept—it is just a table filled with numbers.

For example, the following (3 x 3) matrix, where each number represents the brightness of a pixel (0 is darkest, 1 is brightest):

3x3 grayscale image

A matrix, 9 numbers

[ M = \begin{bmatrix} 0.0 & 0.5 & 1.0 \\ 0.3 & 0.7 & 0.6 \\ 0.8 & 0.2 & 0.4 \end{bmatrix} ]

With this understanding, various image processing operations become clear:

Transpose

img.T

Flip along the diagonal

Horizontal mirror

img[:, ::-1]

Left-right flip

Vertical mirror

img[::-1, :]

Flip up and down

Crop

img[10:54, 10:54]

Extract sub-region

Blur

Convolution kernel sliding mean

Neighborhood average

Rotate

Coordinate Transformation

Matrix Multiplication

When you click a button in Photoshop, NumPy is operating on a two-dimensional array behind the scenes.


Mathematical Definition

A grayscale image of size (H \times W) can be represented as a real-valued matrix:

[ M \in \mathbb{R}^{H \times W}, \quad M_{ij} \in [0, 1] ]

Where (M_{ij}) represents the pixel brightness value of the i-th row and j-th column.

Core concepts of matrix operations:

Operation Mathematical expression NumPy syntax Image effect
Transpose (M^T_{ij} = M_{ji}) img.T Matrix transposition, flip along the diagonal
Horizontal flip (M'{ij} = M{i, W-1-j}) img[:, ::-1] Column index reversal
Vertical flip (M'{ij} = M{H-1-i, j}) img[::-1, :] Reverse row index
Mean blur (M'{ij} = \frac{1}{k^2}\sum{p,q} M_{i+p, j+q}) Sliding window for mean() Replace each pixel with the neighborhood mean

The "sliding window" operation used in mean blurring is essentially the prototype of convolution—the core operation of Convolutional Neural Networks (CNN).


Python hands-on practice

Generate a synthetic grayscale image and implement transpose, flip, crop, and manual convolution blur using NumPy array operations.

Example

import

numpy

as

np

import

matplotlib

matplotlib.

use

(

"Agg"

)

import

matplotlib.

pyplot

as

plt

import

os

Create output directory

OUT

=

os

.

path

.

join

(

os

.

path

.

dirname

(

os

.

path

.

abspath

(

file

)

)

,

"outputs"

)

os

.

makedirs

(

OUT

,

exist_ok

=

True

)

1. Generate a composite grayscale image: diagonal gradient + bright central square

size

=

64

img

=

np.

zeros

(

(

size

,

size

)

)

for

i

in

range

(

size

)

:

   

for

j

in

range

(

size

)

:

        img

[

i

,

j

]

=

(

i + j

)

/

(

2

)

 

Diagonal gradient from dark to light

img

[

20

:

44

,

20

:

44

]

=

0.6

                 

Add a bright block in the middle

img

=

np.

clip

(

img

,

0

,

1

)

                 

Restricted to the range [0, 1]

print

(

"RUNOOB image matrix shape (shape):"

,

img.

shape

)

print

(

"Top-left 3x3 part of the image matrix:\n"

,

np.

round

(

img

[

:

3

,

:

3

]

,

3

)

)

2. Matrix operation = Image transformation

img_transpose

=

img.

T

         

Transpose: swap rows and columns

img_flip_lr

=

img

[

:

,

::-

1

]

     

Horizontal mirror: reverse column index

img_flip_ud

=

img

[

::-

1

,

:

]

     

Vertical mirror: row index inversion

img_crop

=

img

[

10

:

54

,

10

:

54

]

   

Cropping: Slicing to get a submatrix

3. Manual mean blur (5x5 kernel, no OpenCV tuning)

def

box_blur

(

mat

,

k

=

5

)

:

   

"""Apply mean blur to the matrix using a k x k sliding window"""

pad

=

k //

2

   

Boundary padding with edge values (edge padding)

padded

=

np.

pad

(

mat

,

pad

,

mode

=

"edge"

)

out

=

np.

zeros_like

(

mat

)

   

for

i

in

range

(

mat.

shape

[

0

]

)

:

       

for

j

in

range

(

mat.

shape

[

1

]

)

:

           

Take a k x k neighborhood and calculate the mean

out

[

i

,

j

] =

=

padded

[

i:i+k

,

j:j+k

]

.

mean

(

)

   

return

out

img_blur

=

box_blur

(

img

,

k

=

5

)

print

(

RUNOOB blurred matrix top-left 3x3 part:

,

      np.

round

(

img_blur

[

:

3

,

:

3

]

,

3

)

)

4. Save visualization comparison chart

fig

,

axes

=

plt.

subplots

(

2

,

3

,

figsize

=

(

12

,

8

)

)

titles

=

[

"Original image (matrix)"

,

"Transpose img.T"

,

         

"Horizontal mirror img[:, ::-1]"

,

         

"Vertical mirror img[::-1, :]"

,

         

"Crop img[10:54, 10:54]"

,

         

"Mean blur (5x5 convolution)"

]

images

=

[

img

,

img_transpose

,

img_flip_lr

,

img_flip_ud

,

img_crop

,

img_blur

]

for

ax

,

title

,

im

in

zip

(

axes.

flat

,

titles

,

images

)

:

    ax.

imshow

(

im

,

cmap

=

"gray"

,

vmin

=

0

,

vmax

=

1

)

ax.

set_title

(

title

,

fontsize

=

11

)

    ax.

axis

(

"off"

)

plt.

tight_layout

(

)

plt.

savefig

(

os

.

path

.

join

(

OUT

,

"01_image_as_matrix.png"

)

,

dpi

=

130

)

print

(

f

"\nRUNOOB visualization results saved to {OUT}/01_image_as_matrix.png"

)

Original prompt (Chinese, left untranslated)



RUNOOB 图像矩阵形状 (shape): (64, 64)

Top 3x3 part of the image matrix:

 [[0.    0.008 0.016]

 [0.008 0.016 0.023]

 [0.016 0.023 0.031]]

RUNOOB Blurred Matrix Top 3x3 Section:

 [[0.009 0.011 0.013]

 [0.01  0.013 0.016]

 [0.011 0.016 0.021]]

RUNOOB 可视化结果已保存到 .../outputs/01_image_as_matrix.png

As you can see, the numerical difference between adjacent pixels has decreased after blurring—this is the mathematical essence of "blurring": replacing the original pixel value with the neighborhood mean.


Application scenarios in AI

AI scenarios How to use matrices
Convolutional Neural Network (CNN) The input is a 4th-order tensor composed of a batch of images (batch, H, W, C), and each layer slides a convolutional kernel (a small matrix) over the input.
Data Augmentation Randomly flipping, rotating, and cropping images during training—all are matrix operations used to expand the training set.
Image Preprocessing Uniformly cropping to a fixed size (e.g., 224x224) before feeding into the model—this is matrix slicing and scaling.
Style Transfer Representing images as feature matrices and changing the "style" features through matrix operations.

NumPy's ndarray and PyTorch's Tensor are essentially the same thing: a multi-dimensional array of numbers. Once you understand matrices, you understand the most fundamental data structure in deep learning frameworks.