import os
import cv2
import torch
import numpy as np
import random
import cv2 as cv
from matplotlib import pyplot as pltdef f_VerifyConv2D():"""驗證torch.nn.Conv2d, 并將輸入數據及權重保存到txt文件中"""x = torch.randn(1, 1, 10, 10)x = x.round().float()print('================================== 輸入數據 ')print(x)conv_zeros = torch.nn.Conv2d(in_channels=1, out_channels=3, kernel_size=3, stride=1, padding=1, bias=True)conv_zeros.weight = torch.nn.Parameter(torch.ones(1, 1, 3, 3))conv_zeros.bias = torch.nn.Parameter(torch.ones(1))y = conv_zeros(x)print('================================== 卷積權重數據 ')print(conv_zeros.state_dict())print('================================== 卷積輸出數據 ')print(y)# 轉成numpyprint('================================== 保存參數txt ')ndarray = x.numpy()print(ndarray)ndarray = ndarray.reshape(-1).astype(np.int16)ndarray[np.where(ndarray < 0)] = np.add(ndarray[np.where(ndarray < 0)], 255) # 將負數以補碼的形式進行存儲np.savetxt("1.txt", ndarray, fmt='%x', delimiter='\n')f_VerifyConv2D()