import torch
import numpy as np
import random
from IPython import display
from matplotlib import pyplot as plt
import torch.utils.data as Data
from PIL import Image
import os
from torch import nn
import torch.optim as optim
from torch.nn import init
import torch.nn.functional as F
import time
import time
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from matplotlib.pyplot import MultipleLocator
##加入一些训练的时间,还有需要打印的资料
import datetime
import matplotlib
from PIL import Image
from torchvision import transforms
#img = Image.open('1.jpg')
#w, h = img.size
# In[16]:
#自定义单通道卷积
def corr2d(X,K):
'''
X:输入,shape (batch_size,H,W)
K:卷积核,shape (k_h,k_w)
单通道
'''
batch_size,H,W = X.shape
k_h, k_w = K.shape
#初始化结果矩阵
Y = torch.zeros((batch_size,H - k_h + 1,W- k_w + 1))
for i in range(Y.shape[1]):
for j in range(Y.shape [2]):
Y[:,i,j] = (X[:,i:i+k_h,j:j+k_w]* K).sum()
return Y
import cv2
import matplotlib.pyplot as plt
from PIL import Image
from torchvision import transforms as tfs
img = cv2.imread('data/bus/bus001.jpg')
import numpy as np
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
from PIL import Image
import matplotlib.pyplot as plt
im = Image.open('data/bus/bus002.jpg').convert('L') # 读入一张灰度图的图片
im = np.array(im, dtype='float32') # 将其转换为一个矩阵
#im = transforms.Resize([32,32])
#im=im.resize((28,28))
#print(im.shape[0],im.shape[1]) 448*448
# 可视化图片
plt.subplot(211)
plt.imshow(im.astype('uint8'), cmap='gray')
#im = torch.from_numpy(im.reshape((1, 1, im.shape[0], im.shape[1])))
im = torch.from_numpy(im)#.reshape((im.shape[0], im.shape[1])))
batch_size=1
print(im.shape[0])
Y = torch.zeros((batch_size,im.shape[0], im.shape[1]))
for i in range(Y.shape[1]):
for j in range(Y.shape [2]):
Y[:,i,j] = im[i,j]
#return Y
print(Y.shape)
#
X=Y#torch.rand(1,20,20)
k=torch.rand(3,3)
S=corr2d(X,k)
#plt.imshow(S.astype('uint8'), cmap='gray')
import numpy
Y = torch.zeros(S.shape[1], S.shape[2])
for i in range(Y.shape[0]):
for j in range(Y.shape [1]):
Y[i,j] = S[:,i,j]
S=Y
print(S.shape[0], S.shape[1])
plt.subplot(212)
plt.imshow(S) # 显示图片
plt.show()#py)#.reshape((im.shape[0], im.shape[1])))