Numpy处理图片方法

在进行图像领域的深度学习的时候经常需要对图片进行处理,包括图像的翻转,压缩,截取等,一般都是用Numpy来处理。处理起来也很方便。 

In[3]


# 导入需要的包
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

# 读入图片
image = Image.open('./work/vehicle1.jpg')
image = np.array(image)
# 查看数据形状,其形状是[H, W, 3],
# 其中H代表高度, W是宽度,3代表RGB三个通道
image.shape
(437, 700, 3)

In[4]

# 原始图片
plt.imshow(image)
<matplotlib.image.AxesImage at 0x7fb195078b10>

In[7]


# 垂直方向翻转
# 这里使用数组切片的方式来完成,
# 相当于将图片最后一行挪到第一行,
# 倒数第二行挪到第二行,..., 
# 第一行挪到倒数第一行
# 对于行指标,使用::-1来表示切片,
# 负数步长表示以最后一个元素为起点,向左走寻找下一个点
# 对于列指标和RGB通道,仅使用:表示该维度不改变
image2 = image[::-1, :, :]
plt.imshow(image2)
<matplotlib.image.AxesImage at 0x7fecfbfd15d0>

In[8]


# 水平方向翻转
image3 = image[:, ::-1, :]
plt.imshow(image3)
<matplotlib.image.AxesImage at 0x7fecfbf3aa10>

In[5]

# 180度方向翻转
image31 = image[::-1, ::-1, :]
plt.imshow(image31)
<matplotlib.image.AxesImage at 0x7fb194faaf10>

In[9]

# 保存图片
im3 = Image.fromarray(image3)
im3.save('im3.jpg')

In[10]


#  高度方向裁剪
H, W = image.shape[0], image.shape[1]
# 注意此处用整除,H_start必须为整数
H1 = H // 2 
H2 = H
image4 = image[H1:H2, :, :]
plt.imshow(image4)
<matplotlib.image.AxesImage at 0x7fecfbeac6d0>

In[11]


#  宽度方向裁剪
W1 = W//6
W2 = W//3 * 2
image5 = image[:, W1:W2, :]
plt.imshow(image5)
<matplotlib.image.AxesImage at 0x7fecfbe90390>

In[13]


# 两个方向同时裁剪
image5 = image[H1:H2, \
               W1:W2, :]
plt.imshow(image5)
<matplotlib.image.AxesImage at 0x7fecfbd5c810>

In[14]


# 调整亮度
image6 = image * 0.5
plt.imshow(image6.astype('uint8'))
<matplotlib.image.AxesImage at 0x7fecfbd47d10>

In[15]


# 调整亮度
image7 = image * 2.0
# 由于图片的RGB像素值必须在0-255之间,
# 此处使用np.clip进行数值裁剪
image7 = np.clip(image7, \
        a_min=None, a_max=255.)
plt.imshow(image7.astype('uint8'))
<matplotlib.image.AxesImage at 0x7fecfbcbb510>

In[16]


#高度方向每隔一行取像素点
image8 = image[::2, :, :]
plt.imshow(image8)
<matplotlib.image.AxesImage at 0x7fecfbc25850>

In[17]


#宽度方向每隔一列取像素点
image9 = image[:, ::2, :]
plt.imshow(image9)
<matplotlib.image.AxesImage at 0x7fecfbc08710>

In[18]


#间隔行列采样,图像尺寸会减半,清晰度变差
image10 = image[::2, ::2, :]
plt.imshow(image10)
image10.shape
(219, 350, 3)

  • 13
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值