首页 > 编程 > Python > 正文

python读取图片任意范围区域

2020-02-16 00:51:10
字体:
来源:转载
供稿:网友

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

convert 函数

from PIL import Imageimport numpy as npimport matplotlib.pyplot as pltdef 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_datadef 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  |  and the palette can be represented without a palette.  |    |  The current version supports all possible conversions between  |  "L", "RGB" and "CMYK." The **matrix** argument only supports "L"  |  and "RGB".  |    |  When translating a color image to black and white (mode "L"),  |  the library uses the ITU-R 601-2 luma transform::  |    |   L = R * 299/1000 + G * 587/1000 + B * 114/1000  |    |  The default method of converting a greyscale ("L") or "RGB"  |  image into a bilevel (mode "1") image uses Floyd-Steinberg  |  dither to approximate the original image luminosity levels. If  |  dither is NONE, all non-zero values are set to 255 (white). To  |  use other thresholds, use the :py:meth:`~PIL.Image.Image.point`  |  method.  |    |  :param mode: The requested mode. See: :ref:`concept-modes`.  |  :param matrix: An optional conversion matrix. If given, this  |   should be 4- or 12-tuple containing floating point values.  |  :param dither: Dithering method, used when converting from  |   mode "RGB" to "P" or from "RGB" or "L" to "1".  |   Available methods are NONE or FLOYDSTEINBERG (default).  |  :param palette: Palette to use when converting from mode "RGB"  |   to "P". Available palettes are WEB or ADAPTIVE.  |  :param colors: Number of colors to use for the ADAPTIVE palette.  |   Defaults to 256.  |  :rtype: :py:class:`~PIL.Image.Image`  |  :returns: An :py:class:`~PIL.Image.Image` object.'''

原图:

filepath = "./imgs/"imgdata = ImageToMatrix("./imgs/0001.jpg")print(type(imgdata))print(imgdata.shape)plt.imshow(imgdata) # 显示图片plt.axis('off')  # 不显示坐标轴plt.show()

运行结果:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表