python读取图片的方式,以及将图片以三维数组的形式输出方法

yipeiwu_com6年前Python基础

近期做个小项目需要用到python读取图片,自己整理了一下两种读取图片的方式,其中一种用到了TensorFlow,(TensorFlow是基于python3 的)。代码及运行结果如下所示:

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

image = Image.open(r'C:\Users\Administrator\Desktop\data\train\forest_001.jpg')  #读取图片文件
plt.imshow(image)
plt.show()      #将图片输出到屏幕

image_arr = np.array(image)   #将图片以数组的形式读入变量
print (image_arr)

另一种读取图片的方式

# coding=utf-8
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

image_contents = tf.read_file(r'C:\Users\Administrator\Desktop\data\train\forest_001.jpg')  #读取文件

image = tf.image.decode_jpeg(image_contents, channels=3)   #解码jpeg

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())

  img=sess.run((image))     #img为三维数组
  print (img.shape)     #输出数组形状
  print (img)           #打印数组

  plt.imshow(img)    #显示数组
  plt.show()

结果为:

打印图片

输出的数组部分截图

以上这篇python读取图片的方式,以及将图片以三维数组的形式输出方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

跟老齐学Python之用Python计算

一提到计算机,当然现在更多人把她叫做电脑,这两个词都是指computer。不管什么,只要提到她,普遍都会想到她能够比较快地做加减乘除,甚至乘方开方等。乃至于,有的人在口语中区分不开计算机...

Python编程中对文件和存储器的读写示例

1.文件的写入和读取 #!/usr/bin/python # -*- coding: utf-8 -*- # Filename: using_file.py # 文件是创建和读...

用Python读取几十万行文本数据

我在使用python读取几十万行的文件中的数据,并构造字典,列表等数据结构时,再访问字典,列表时,一般都会出现内存不够的问题,然后只能循环读取几百行或者一定数量的行数来循环操作。 k...

tensorflow 用矩阵运算替换for循环 用tf.tile而不写for的方法

如下所示: # u [32,30,200] # u_logits [400,32,30] q_j_400 = [] for j in range(400): q_j_400.ap...

PyQt5组件读取参数的实例

1.QLineEdit QLineEdit.text() #输出str类型 2.QCheckBox QCheckBox.checkState() #状态 选定: int(QCh...