import tensorflow as tf
import os
import matplotlib.pyplot as plt
filename='/home/ubuntu/images/1.jpeg'
img = tf.gfile.FastGFile(filename, 'r').read() #读取三通道图片
image_data = tf.image.decode_jpeg(img)#进行编码
image_show = tf.image.convert_image_dtype(image_data, dtype = tf.float32)#tensorflow中操作多为浮点型,而图片多为int型,故作此转化
image_batch = tf.expand_dims(image_show, 0)#原来的单张图片为三维(height,width,channel)而下文中卷积核定义为四维(batchsize,height,width,channel),因此通过该方法在0维添加一维,相当于将原来的单张图片三维数据放在一个另一个集合中从而形成四维
#边缘检测滤波器
kernel=tf.constant([
[
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]],
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]],
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]]
],
[
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]],
[[8.,0.,0.],[0.,8.,0.],[0.,0.,8.]],
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]]
],
[
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]],
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]],
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]]
]
])
with tf.Session() as sess:
sess.run(image_show)
plt.imshow(image_show.eval())
plt.show()#读入tensorflow后画出原图
conv2d=tf.nn.conv2d(image_batch,kernel,[1,1,1,1],padding='SAME')
activation_map=sess.run(tf.minimum(tf.nn.relu(conv2d),255))#激活措施加均值操作将颜色值置于(0~255)以内的区间
print activation_map.shape
encoded_image=activation_map.reshape([720,1280,3])#注意该步骤将得到的四维np.array数据还原为三维。plt显示的前提
#encoded_image = tf.image.encode_jpeg(activation_map)
#with tf.gfile.GFile('/home/ubuntu/images/output.jpg', 'wb') as f:
#plt(encoded_image.eval())
#plt.show()
#f.write(encoded_image.eval())
active= tf.image.convert_image_dtype(encoded_image, dtype = tf.float32)
plt.imshow(active.eval())
plt.show()