卷积神经网络学习

一.简单黑白边界检测

代码

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([0,-2,2], 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([60,60], dtype='float32')
img[:, 30:] = 0.

x = img.reshape([1,1,60,60])

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)

运行截图

卷积神经网络学习_第1张图片

二.图像中物体边缘化检测

代码

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"

Ha_Shiqi = Image.open('img/hashiqi.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(Ha_Shiqi).astype('float32')

x = np.transpose(x, (2, 0, 1))

x = x.reshape(1, 3, Ha_Shiqi.height, Ha_Shiqi.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(Ha_Shiqi)
f = plt.subplot(122)
f.set_title('output feature image', fontsize=20)
plt.imshow(out.squeeze(), cmap='gray')
plt.show()

运行截图

卷积神经网络学习_第2张图片

图像均值模糊

代码

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"


boshimao = Image.open('img/boshimiao.jpg').convert('L')
boshimao = np.array(boshimao)


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 = boshimao.astype('float32')
x = x.reshape([1, 1, boshimao.shape[0], boshimao.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(boshimao, cmap='gray')

f = plt.subplot(122)
f.set_title('output feature map', fontsize=20)
out = out.squeeze()
plt.imshow(out, cmap='gray')
plt.show()


运行结果

卷积神经网络学习_第3张图片

万圣节快乐

你可能感兴趣的:(1024程序员节)