【tensorflow】使用convolution处理图片

筅森魡賤 提交于 2019-12-10 18:46:35
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import tensorflow as tf 
# plt.figure(figsize=(12,9))
 
image = plt.imread('./caise.jpg')
plt.imshow(image)
image.shape

(388, 690, 3)

在这里插入图片描述

data = image.reshape(1,388, 690, 3).astype(np.float32)

# and a filter / kernel tensor of shape
# `[filter_height, filter_width, in_channels, out_channels]
filter_ = np.array([[1/27]*81]).reshape(3,3,3,3)
conv = tf.nn.conv2d(data,filter_,[1,1,1,1],'SAME')
with tf.Session() as sess:
    image = sess.run(conv).reshape(388, 690,3)
plt.imshow(image.astype(np.uint8))

在这里插入图片描述

388*690*3

803160

data = image.reshape(1,388, 690, 3).astype(np.float32)
# and a filter / kernel tensor of shape
# `[filter_height, filter_width, in_channels, out_channels]
filter_ = np.random.rand(3,3,3,3)/13
conv = tf.nn.conv2d(data,filter_,[1,1,1,1],'SAME')
with tf.Session() as sess:
    image = sess.run(conv).reshape(388, 690,3)
plt.imshow(image.astype(np.uint8))

在这里插入图片描述

卷积,对每个通道进行卷积运算

data = image.reshape(1,388, 690, 3).astype(np.float32)

# data.shape = (3,662,1000,1)
data = np.transpose(data,axes = [3,1,2,0])

# and a filter / kernel tensor of shape
# `[filter_height, filter_width, in_channels, out_channels]
filter_ = np.array([[1/9]*9]).reshape(3,3,1,1)

conv = tf.nn.conv2d(data,filter_,[1,1,1,1],'SAME')
with tf.Session() as sess:
    result = sess.run(conv).reshape(3,388, 690)
    result = np.transpose(result,[1,2,0])
    print(result.shape)
plt.figure(figsize=(16,12))
plt.imshow(result.astype(np.uint8))

(388, 690, 3)

在这里插入图片描述

加模糊程度

data = image.reshape(1,388, 690,3).astype(np.float32)

# data.shape = (3,662,1000,1)
data = np.transpose(data,axes = [3,1,2,0])

# and a filter / kernel tensor of shape
# `[filter_height, filter_width, in_channels, out_channels]
filter_ = np.array([[1/49]*49]).reshape(7,7,1,1)

conv = tf.nn.conv2d(data,filter_,[1,1,1,1],'SAME')
with tf.Session() as sess:
    result = sess.run(conv).reshape(3,388, 690)
    result = np.transpose(result,[1,2,0])
    print(result.shape)
plt.figure(figsize=(16,12))
plt.imshow(result.astype(np.uint8))

(388, 690, 3)

在这里插入图片描述

# 替代imag内容 不模糊
plt.imshow(image[330:380,280:420])

在这里插入图片描述



data = image.reshape(1,388, 690,3).astype(np.float32)

# data.shape = (3,662,1000,1)
data = np.transpose(data,axes = [3,1,2,0])

# and a filter / kernel tensor of shape
# `[filter_height, filter_width, in_channels, out_channels]
filter_ = np.array([[1/49]*49]).reshape(7,7,1,1)

conv = tf.nn.conv2d(data,filter_,[1,1,1,1],'SAME')
with tf.Session() as sess:
    result = sess.run(conv).reshape(3,388, 690,)
    result = np.transpose(result,[1,2,0])
    print(result.shape)
plt.figure(figsize=(16,12))
result = result.astype(np.uint8)

result[330:380,280:420]= image[330:380,280:420]

plt.imshow(result)
(388, 690, 3)

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!