python读取图片任意范围区域
作者:sinat_34022298 发布时间:2023-07-16 06:26:21
标签:python,读取图片
使用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
| 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()
运行结果:
mpimg 函数
import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片
import numpy as np
def readPic(picname, filename):
img = mpimg.imread(picname)
# 此时 img 就已经是一个 np.array 了,可以对它进行任意处理
weight,height,n = img.shape #(512, 512, 3)
print("the original pic: \n" + str(img))
plt.imshow(img) # 显示图片
plt.axis('off') # 不显示坐标轴
plt.show()
# 取reshape后的矩阵的第一维度数据,即所需要的数据列表
img_reshape = img.reshape(1,weight*height*n)[0]
print("the 1-d image data :\n "+str(img_reshape))
# 截取(300,300)区域的一小块(12*12*3),将该区域的图像数据转换为一维数组
img_cov = np.random.randint(1,2,(12,12,3)) # 这里使用np.ones()初始化数组,会出现数组元素为float类型,使用np.random.randint确保其为int型
for j in range(12):
for i in range(12):
img_cov[i][j] = img[300+i][300+j]
img_reshape = img_cov.reshape(1,12*12*3)[0]
print((img_cov))
print(img_reshape)
# 打印该12*12*3区域的图像
plt.imshow(img_cov)
plt.axis('off')
plt.show()
# 写文件
# open:以append方式打开文件,如果没找到对应的文件,则创建该名称的文件
with open(filename, 'a') as f:
f.write(str(img_reshape))
return img_reshape
if __name__ == '__main__':
picname = './imgs/0001.jpg'
readPic(picname, "data.py")
读出的数据(12*12*3),每个像素点以R、G、B的顺序排列,以及该区域显示为图片的效果:
参考:python 读取并显示图片的两种方法
来源:https://blog.csdn.net/sinat_34022298/article/details/79533934


猜你喜欢
- 开始制作符合标准的站点,第一件事情就是声明符合自己需要的DOCTYPE。查看本站首页原代码,可以看到第一行就是:<!DOCTYPE h
- 函数:endswith()作用:判断字符串是否以指定字符或子字符串结尾,常用于判断文件类型相关函数:判断字符串开头 startswith()
- 本文介绍了详解vue 模版组件的三种用法,分享给大家,具体如下:第一种//首先,别忘了引入vue.js<div id="us
- 什么是 Goroutinegoroutine 是 Go 并行设计的核心。goroutine 说到底其实就是协程,它比线程更小,十几个 gor
- 使用PHP编写程序的时候,我们常常想要获取当前页面的URL。下面提供一个用于获取当前页面URL的函数以及使用方法:示例一:<?php/
- 本人最近在学习python,在看了一些教程后,用python写了一个简单的云音乐播放器,下面把主要代码贴上来,其中用到了github上他人写
- 一、安装在 cmd 命令中输入: pip install pygame即可安装成功了二、第一个代码实例代码快里面有注释,想必大家都可以看懂的
- 获取指定日期月份的第一天,你可以使用DATEADD函数,减去指定日期的月份过去了的天数,即可。 代码如下:CREATE FUNC
- 编者注:当讲到了性能优化和案例方面的东西,就要想到如何从开发人员的角度进行了理解,认识SQL是如何执行,以及如何学习高级的SQL,这篇文章对
- 这个错误是最新的错误哈,目前只在tensorflow上的github仓库上面有提出,所以你在百度上面找不到。是个tensorflow的bug
- 一、效果展示话不多说先上效果为了更有意境我加了个完美的背景来衬托出月饼的好看我的月饼画的不圆的原因是我故意的,为什么呢?因为月有阴晴圆缺啊!
- python3.x已经不支持mysqldb了,支持的是pymysql使用pandas读取MySQL数据时,使用sqlalchemy,出现No
- 前面使用TensorFlow实现一个完整的Softmax Regression,并在MNIST数据及上取得了约92%的正确率。前文传送门:
- Matplotlib编程实现import matplotlib.pyplot as pltimport numpy as npfrom ma
- #!/usr/bin/env python#coding=utf-8import osfrom pyinotify import Watch
- OUTLINE 常见的时间字符串与timestamp之间的转换日期与timestamp之间的转换常见的时间字符串与timesta
- 1、下载地址:MySQL官网2、解压解压之后的文件里边是没有data文件的,需要创建一个空文件夹命名为data(后面需要用),并且需要创建一
- 什么是JSONP首先提一下JSON这个概念,JSON是一种轻量级的数据传输格式,被广泛应用于当前Web应用中。JSON格式数据的编码和解析基
- 一般数据库默认是10次尝试失败后锁住用户 1、查看FAILED_LOGIN_ATTEMPTS的值selec
- map()是一个 Python 内建函数,它允许你不需要使用循环就可以编写简洁的代码。一、Python map() 函数这个map()函数采