卷积算子的应用
- 一、简单的黑白边界检测
- 代码实现
-
- 二、图像中物体边缘检测
-
- 三、图像均值模糊
-
一、简单的黑白边界检测
代码实现
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([0, -1, 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([55, 55], dtype='float32')
img[:, 25:] = 0.
x1 = img.reshape([1, 1, 55, 55])
x2 = paddle.to_tensor(x1)
y = conv(x2)
out = y.numpy()
f = plt.subplot(121)
f.set_title('input image', fontsize=20)
plt.imshow(img, cmap='gray')
f = plt.subplot(122)
f.set_title('output featuremap', fontsize=20)
plt.imshow(out.squeeze(), cmap='gray')
plt.show()
运行截图
二、图像中物体边缘检测
代码实现
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()
运行结果
原图
边缘检测图
三、图像均值模糊
代码实现
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()
运行结果