卷积神经网络学习

案例一——简单的黑白边界检测 

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()

运行结果如下:

卷积神经网络学习_第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
img=Image.open(r'D:\Users\DELL\PycharmProjects\paddle\222.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()

卷积神经网络学习_第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

img = Image.open(r'D:\Users\DELL\PycharmProjects\paddle\222.jpg').convert('L')
img = np.array(img)

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

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

plt.show()

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

 

你可能感兴趣的:(python,numpy)