1. 引言
嘿,各位屏幕前的探险家们,你们是不是也曾对着电脑屏幕上的图像数据,心里默默念叨:“这像素小方块,到底藏着多少未解之谜?”别怕,今天咱们不玩星际穿越,也不搞量子纠缠,咱们就来一场说走就走的“Matplotlib图像处理之旅”!想象一下,你手握一把名为“Matplotlib”的魔法棒,轻轻一挥,那些单调的图表瞬间变身五彩斑斓的艺术品,数据背后的故事跃然屏上。不用念咒语,也不用求神仙,跟着我的步伐,咱们一起把数据处理这活儿,玩出花儿来!准备好了吗?咱们的图像处理大冒险,即刻启程!
2. 导包
# 导包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
3. 读取图片
- imread
img = plt.imread("16_matplotlib.jpg")
img
array([[[ 40, 84, 155],
[ 40, 84, 155],
[ 40, 84, 155],
...,
[ 39, 83, 154],
[ 38, 82, 153],
[ 38, 82, 153]],
[[ 40, 84, 155],
[ 40, 84, 155],
[ 40, 84, 155],
...,
[ 40, 84, 155],
[ 39, 83, 154],
[ 39, 83, 154]],
[[ 40, 84, 155],
[ 40, 84, 155],
[ 40, 84, 155],
...,
[ 41, 85, 156],
[ 41, 85, 156],
[ 41, 85, 156]],
...,
[[165, 205, 255],
[157, 197, 248],
[140, 180, 232],
...,
[ 70, 112, 184],
[ 73, 115, 187],
[ 73, 115, 189]],
[[179, 220, 255],
[172, 212, 255],
[155, 195, 246],
...,
[ 71, 113, 185],
[ 75, 117, 189],
[ 74, 116, 190]],
[[182, 223, 255],
[175, 216, 255],
[158, 198, 249],
...,
[ 72, 114, 186],
[ 76, 118, 190],
[ 76, 118, 192]]], dtype=uint8)
# 查看图片形状(宽度/高度/每个像素点图片的值)
img.shape
(600, 960, 3)
# 图片颜色
# 三原色:RGB(Red,Green,Blue)
# 范围:0-255(000,000,000:表示黑色;255,255,255:表示白色)
# 彩色图:三维数据
# 黑白图:二维数据
4. 显示图片
- imshow
plt.imshow(img)
<matplotlib.image.AxesImage at 0x22f1512afd0>
# 垂直翻转:上下翻转
plt.imshow(img, origin="lower")
<matplotlib.image.AxesImage at 0x22f15b5b490>
# 第二种写法
plt.imshow(img[::-1])
<matplotlib.image.AxesImage at 0x22f15b73490>
# 水平翻转:左右翻转
plt.imshow(img[:, ::-1])
<matplotlib.image.AxesImage at 0x22f154501d0>
# 截取一部分
plt.imshow(img[100:400, 180:800])
<matplotlib.image.AxesImage at 0x22f16024fd0>
5. 保存图片
- imsave
# 截取图片
img2 = img[100:400, 180:800]
# 将截取之后的图片保存
plt.imsave("16_matplotlib_split.png", img2)