# 将自己的神经网络部署的到 MaixII-Dock 上

2022年1月26日 Rui 编写文档 ---

## 边缘检测原理介绍

[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]


[1, 2, 1],
[0, 0, 0],
[-1, -2, -1]


out = np.sqrt(np.square(out_v) + np.square(out_h))
plt.imshow(out)


out = np.sqrt(np.square(out_v) + np.square(out_h))
out = out * 255.0 / out.max()
plt.imshow(out.astype(np.uint8))


## 定义卷积核

[-1, -1, -1],
[ -1, 8, -1],
[ -1, -1, -1]


# 全边缘卷积核
conv_rgb_core_sobel = [
[[-1,-1,-1],[-1,8,-1], [-1,-1,-1],
[0,0,0],[0,0,0], [0,0,0],
[0,0,0],[0,0,0], [0,0,0]
],

[[0,0,0],[0,0,0], [0,0,0],
[-1,-1,-1],[-1,8,-1], [-1,-1,-1],
[0,0,0],[0,0,0], [0,0,0]
],a

[[0,0,0],[0,0,0], [0,0,0],
[0,0,0],[0,0,0], [0,0,0],
[-1,-1,-1],[-1,8,-1], [-1,-1,-1],
]]


## 代码实现边缘检测

### 定义网络模型

import torch
import torch.nn as nn
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 3, 3, padding=(0, 0), bias=False)
def forward(self, x):
x = self.conv1(x)
return x
net = Net()


### 定义卷积核参数

conv_rgb_core_sobel = [
[[-1,-1,-1],[-1,8,-1], [-1,    -1,    -1],
[0,0,0],[0,0,0], [0,0,0],
[0,0,0],[0,0,0], [0,0,0]
],
[[0,0,0],[0,0,0], [0,0,0],
[-1,-1,-1],[-1,8,-1], [-1,    -1,    -1],
[0,0,0],[0,0,0], [0,0,0]
],
[[0,0,0],[0,0,0], [0,0,0],
[0,0,0],[0,0,0], [0,0,0],
[-1,-1,-1],[-1,8,-1], [-1,    -1,    -1],
]]


### 定义载入权重函数

def sobel(net, kernel):
sobel_kernel = np.array(kernel,    dtype='float32')
sobel_kernel = sobel_kernel.reshape((3,    3,    3,    3))
net.conv1.weight.data = torch.from_numpy(sobel_kernel)
params = list(net.parameters())


### 输入数据进行处理

pil_img = Image.open("./images/class1_5.jpg")
display(pil_img)
input_img = np.array(pil_img)
print(input_img.shape)


# 归一化处理
input_tensor = (input_img.astype(np.float32) - 127.5) / 128 # to [-1, 1]
print(input_tensor.shape)
input_tensor = torch.Tensor(input_tensor).permute((2, 0, 1))
input_tensor = input_tensor.unsqueeze(0)
print("input shape:", input_tensor.shape)

# 转换成 PyTorch 张量
input_tensor = (input_img.astype(np.float32) - 127.5) / 128 # to [-1, 1]
input_tensor = torch.Tensor(input_tensor).permute((2, 0, 1))
print(input_tensor.shape)
input_tensor = input_tensor.unsqueeze(0)
print("input shape:", input_tensor.shape)


### 进行边缘检测

# 载入网络权重
sobel(net, conv_rgb_core_sobel)

# 输入图片到网络中进行处理
out = net(input_tensor)
sobel_img_t = out.numpy()[0].transpose([1,2,0])

# 显示输出结果
plt.figure()
plt.subplot(1, 5, 1)
plt.imshow(input_img)
plt.subplot(1, 5, 2)
plt.imshow(sobel_img_t)