python 读取图片任意范围,以一维数组形式返回

使用python进行图片处理,现在需要读出图片的任意一块区域,并将其转化为一维数组,方便后续卷积操作的使用。 下面使用两种方法进行处理:convert 函数from PIL import Imageimport numpy as npimport matplotlib.pyplot as pltdef ImageToMatrix(filename): im = Imag...
摘要由CSDN通过智能技术生成

使用python进行图片处理,现在需要读出图片的任意一块区域,并将其转化为一维数组,方便后续卷积操作的使用。
下面使用两种方法进行处理:

convert 函数


from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

def ImageToMatrix(filename):
    im = Image.open(filename)        # 读取图片
    im.show()                        # 显示图片
    width,height = im.size
    print("width is :" + str(width))
    print("height is :" + str(height))
    im = im.convert("L")             # pic --> mat 转换,可以选择不同的模式,下面有函数源码具体说明
    data = im.getdata()
    data = np.matrix(data,dtype='float')/255.0
    new_data = np.reshape(data * 255.0,(height,width))
    new_im = Image.fromarray(new_data)
    # 显示从矩阵数据得到的图片
    new_im.show()
    return new_data

def MatrixToImage(data):
    data = data*255
    new_im = Image.fromarray(data.astype(np.uint8))
    return new_im

'''
  convert(self, mode=None, matrix=None, dither=None, palette=0, colors=256)
     |      Returns a converted copy of this image. For the "P" mode, this
     |      method translates pixels through the palette.  If mode is
     |      omitted, a mode is chosen so that all information in the image
     |      <
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值