#案例一:
import matplotlib.pyplot as plt
import numpy as np
import paddle
from paddle.nn import Conv2D
from paddle.nn.initializer import Assign
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)
案例二:
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
img = Image.open('F:\pycharm\pycharm\pyC\chk.jpg')
w = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype='float32') / 8
w = w.reshape([1, 1, 3, 3])
w = np.repeat(w, 3, axis=1)
conv = Conv2D(in_channels=3, out_channels=1, kernel_size=[3, 3],
weight_attr=paddle.ParamAttr(
initializer=Assign(value=w)))
x = np.array(img).astype('float32')
x = np.transpose(x, (2, 0, 1))
x = x.reshape(1, 3, img.height, img.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=15)
plt.imshow(img)
f = plt.subplot(122)
f.set_title('output feature map', fontsize=15)
plt.imshow(out.squeeze(), cmap='gray')
plt.show()
使用PaddlePaddle实现卷积神经网络及图像处理
该博客展示了如何利用PaddlePaddle库构建卷积神经网络(CNN),并应用到图像处理中。通过两个案例,分别演示了如何初始化权重并应用一维和三维卷积核来处理图像,输出特征图。案例一中,输入图像经过1x3卷积核处理;案例二中,使用3x3卷积核对彩色图像进行处理。最后,将处理后的图像以灰度图形式展示。
8445

被折叠的 条评论
为什么被折叠?



