An article to understand what the essence of images is

What is an image?
Each picture can be seen as an array
insert image description here

insert image description hereWhat about color pictures?
#pic_center =500x500
insert image description herecolor picture in computer eyes
insert image description here
Numpy reads color photos

insert image description here
• Shape three-dimensional array
• height
• width
• color channel
Numpy reads color photo
• photo size 540 x 480
• 540 pixel width
• 480 pixel height
• 3 color channels
• Numpy shape (480 , 540, 3)
• row: 480 pixels high
• column: 540 pixels wide
• 3 color channels

insert image description hereThe computer doesn't know which channel
is red, it only knows that there are three
channels that represent the value of the color

So we need to mark the color corresponding to the channel.
Each channel is essentially equivalent to a
grayscale image .

#首先导入numpy
import numpy as np
# 为了在notebook中显示图片,导入matplotlib库
import matplotlib.pyplot as plt

# 加这行在Notebook显示图像
%matplotlib inline
#再使用一个PIL库,用于读取图像
from PIL import Image
#演示
img = Image.open("./img/cat.jpg")
#显示图像
img

insert image description here

#打印一下变量的类型
type(img)
# 可以看到这个不是numpy的数组格式,那numpy还不能处理它
img_arr = np.asarray(img)
type(img_arr)
# 发现已经变成了numpy数组,现在我们就可以用numpy来处理它了
img_arr.shape
# 可以看到这张照片是1880像素宽,1253像素高,3个颜色通道
# 再使用matplot的imshow()方法显示Numpy数组形式的图片
plt.imshow(img_arr)

insert image description here

# 可以看到横坐标和纵坐标显示了图片的长度是1800多,高度是1200多
# 我们继续对这个图片操作,先使用numpy的copy方法复制一份原图
img_arr_copy = img_arr.copy()
plt.imshow(img_arr_copy)

insert image description here

#检查一下大小
img_arr_copy.shape
# 首先使用numpy切片,将R,G,B三个颜色通道中的R红色通道显示出来
plt.imshow(img_arr_copy[:,:,0])

insert image description here

# 大家会发现这个颜色很奇怪,都是翠绿色,为什么会显示成这样呢?

# 我们打开matplot的官网关于颜色表colormap的说明:
# https://matplotlib.org/stable/gallery/color/colormap_reference.html
# 可以看到默认的颜色:是翠绿色(viridis )。那这个颜色方便色盲观看的
# 我们也可以将cmap颜色设置成火山岩浆样式:magma
plt.imshow(img_arr_copy[:,:,1],cmap="magma")

insert image description here

# 我们打印一下红色R通道的数组
img_arr_copy[:,:,0]
# 好,我们知道,计算机是分不清到底哪一个通道是红色的,每一个颜色通道其实都是一个灰度图,我们首先将cmap颜色设置为gray灰度
# 看一下
plt.imshow(img_arr_copy[:,:,0],cmap="gray")

insert image description here

# 类似的,我们将绿色通道也显示为灰度模式
plt.imshow(img_arr_copy[:,:,1],cmap='gray')

insert image description here

# 那 0呢代表没有绿色或纯黑色,255呢就代表纯绿色
# 可以看到,灰度图上颜色越浅,表示这里越绿
# 再看一下蓝色通道

plt.imshow(img_arr_copy[:,:,2],cmap='gray')

insert image description here

# 0:没有蓝色或纯黑色,255代表纯蓝色
# 灰度图颜色越浅,表示这里越蓝 ,可以看到这里相比前面红色、绿色的灰度图,这个花瓶是颜色比较浅的,代表颜色接近蓝色
# 当然,我们可以将某个颜色通道颜色全部设为0,我们看一下效果,
# 我这里把绿色通道全部变为0
img_arr_copy[:,:,1] = 0
# 显示一下
plt.imshow(img_arr_copy)

insert image description here

Guess you like

Origin blog.csdn.net/qq_60498436/article/details/132278243