一.卷积神经网络物体边缘检测
代码
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import paddle
from paddle.nn import Conv2D
from paddle.nn.initializer import Assign
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
tree = Image.open('img/c.jpg')
# 设置卷积核参数
w = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype='float32') / 8
w = w.reshape([1, 1, 3, 3])
# 由于输入通道数是3,将卷积核的形状从[1,1,3,3]调整为[1,3,3,3]
w = np.repeat(w, 3, axis=1)
# 创建卷积算子,输出通道数为1,卷积核大小为3x3,
# 并使用上面的设置好的数值作为卷积核权重的初始化参数
conv = Conv2D(in_channels=3, out_channels=1, kernel_size=[3, 3],
weight_attr=paddle.ParamAttr(initializer=Assign(value=w)))
# 将读入的图片转化为float32类型的numpy.ndarray
x = np.array(tree).astype('float32')
# 图片读入成ndarray时,形状是[H,W,3],将通道这一维度调整到最前面
x = np.transpose(x, (2, 0, 1))
# 将数据形状调整成[N,C,H,W]格式
x = x.reshape([1, 3, tree.height, tree.width])
x = paddle.to_tensor(x)
y = conv(x)
out = y.numpy()
plt.figure(figsize=(20, 10))
f = plt.subplot(121)
f.set_title('input image', fontsize=20)
plt.imshow(tree)
f = plt.subplot(122)
f.set_title('output feature image', fontsize=20)
plt.imshow(out.squeeze(), cmap='gray')
plt.show()
结果
二.卷积神经网络均值模糊
代码
import paddle
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from paddle.nn import Conv2D
from paddle.nn.initializer import Assign
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# 读入图片并转换成numpy.ndarray
# 将原图片转换成灰度图
tree = Image.open('img/c.jpg').convert('L')
tree = np.array(tree)
# 创建初始化参数
w = np.ones([1, 1, 5, 5], dtype='float32') / 25
conv = Conv2D(in_channels=1, out_channels=1, kernel_size=[5, 5],
weight_attr=paddle.ParamAttr(initializer=Assign(value=w)))
x = tree.astype('float32')
x = x.reshape([1, 1, tree.shape[0], tree.shape[1]])
x = paddle.to_tensor(x)
y = conv(x)
out = y.numpy()
plt.figure(figsize=(20, 12))
f = plt.subplot(121)
f.set_title('input image', fontsize=20)
plt.imshow(tree, cmap='gray')
f = plt.subplot(122)
f.set_title('output feature map', fontsize=20)
out = out.squeeze()
plt.imshow(out, cmap='gray')
plt.show()
结果
三.卷积神经网络简单黑白边界检测
代码
""" import matplotlib.pyplot as plt
import numpy as np
import paddle
from paddle.nn import Conv2D
from paddle.nn.initializer import Assign
%matplotlib inline
w = np.array([1, 0, -1], dtype='float32')
w = w.reshape([1, 1, 1, 3])
conv = Conv2D(in_channels=1, out_channels=1, kernel_size=[1, 3],
weight_attr=paddle.ParamAttr(
initializer=Assign(value=w)))
img = np.ones([50,50], dtype='float32')
img[:, 30:] = 0.
x = img.reshape([1,1,50,50])
x = paddle.to_tensor(x)
y = conv(x)
out = y.numpy()
f = plt.subplot(121)
f.set_title('input image', fontsize=15)
plt.imshow(img, cmap='gray')
f = plt.subplot(122)
f.set_title('output featuremap', fontsize=15)
plt.imshow(out.squeeze(), cmap='gray')
plt.show()
print(conv.weight)
print(conv.bias)
"""
结果