TensorFlow提取图片所有像素点的RGB数值对,并存入本地磁盘文件后再原样读取显示此图片

备注: 实验原图
在这里插入图片描述

一、功能说明:

综述: jpg格式图片的每个像素点是由类似(223,223,223)这样0~255中的三个数字对组成的。

1、下面我们就要提取输入图片的所有RGB数值对并写入本地磁盘文件中

2、读取磁盘文件中的RGB数值对,用matplotlib将这些RGB数值对以图片形式显示

3、中途可以试着打乱这些RGB数值对,可得到一些意想不到的图片变换哦

二、直接码上:
import numpy as np
import numpy
from numpy.core.defchararray import decode
import tensorflow as tf
import os
from tensorflow.python.ops.image_ops_impl import ResizeMethod
import tensorflow as tf
import matplotlib.pylab as plt


path = 'C:\\Users\\Administrator\\Desktop\\girl.jpg'	# 实验原图本地路径
target='C:\\Users\\Administrator\\Desktop\\girl.txt'	# RGB数值对保存路径

# 读取图片数据
image = tf.compat.v1.read_file(path, 'r')

# 将图像文件解码为Tensor
image_tensor = tf.image.decode_jpeg(image)
image_tensor_numpy = image_tensor.numpy()
print('#######################################################################')


# 图像各 像素点 数值对 写入文件
try:
    # coding=UTF-8,写入多行取消注释即可
    with open(target, 'w',encoding="UTF-8") as file_object:
        for h in range(image_tensor.shape[0]):
            for w in range(image_tensor.shape[1]):
                for i in range(image_tensor.shape[2]):
                    file_object.write(image_tensor_numpy[h][w][i].astype(np.str)+'\t')
                file_object.write('\r\n')   # 每输入一个像素点数值对(3个一对)后换一行
finally:
    file_object.close()


# 读取文件 像素点 数值对
file = open(target, 'r',encoding="utf-8")
image_tensor_init = tf.zeros(shape=(image_tensor.shape[0],image_tensor.shape[1],image_tensor.shape[2]))
tensor_string = None
try:
    tensor_string=file.read()                       
finally:
    file.close()
   
# 将本地的字符串转换为numpy整数列表    
tensor_string_str=tensor_string.replace('\n','')
tensor_string_list = tensor_string_str.split('\t')
array_numpy = np.array(tensor_string_list[:-1])
array_numpy = array_numpy.astype(np.int)
# 将numpy形式整数列表转换为tensor形式整数张量向量
numpy_to_tensor = tf.convert_to_tensor(array_numpy)
# image_numpy_to_tensor = tf.reshape(numpy_to_tensor,(image_tensor.shape[0], image_tensor.shape[1], image_tensor.shape[2]))
image_numpy_to_tensor = tf.reshape(numpy_to_tensor,(800, 575, 3))# 改变tensor向量形状	
# image_numpy_to_tensor = tf.reshape(numpy_to_tensor,(500, 920, 3))# 改变tensor向量形状

print(image_numpy_to_tensor)
print(type(image_numpy_to_tensor))

# # 显示图片
plt.imshow(image_numpy_to_tensor)
plt.show()

三、结果展示:

1.1、 形状为(800, 575, 3)的后台展示:
在这里插入图片描述
1.2、 形状为(800, 575, 3)的matplotlib绘图展示:
在这里插入图片描述
1.3、 形状为(800, 575, 3)的写入本地文件内容展示:
注意: 由于文件行数(460000行)过于大,打开有点慢,静等!!!
在这里插入图片描述

2.1、 形状为(500, 920, 3)的matplotlib绘图展示:
在这里插入图片描述
特别提醒: 本代码基于TensorFlow2.3.0,所以读取图片数据时为了兼容版本:

image = tf.compat.v1.read_file(path, ‘r’)
用了 tf.compat.v1,如果你是TensorFlow1系列的版本,直接tf.read_file(path, ‘r’)即可

此外,为了好玩,改变tensor向量形状时,确保形状格式为:
(height, width, 3),其中height * width=460000;
同理,如果你用自定义图片,请确保最后一维3保持不变,而height * width要等于记事本中显示的行数即可!!!

猜你喜欢

转载自blog.csdn.net/weixin_47834823/article/details/109080387