热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python实现朴素的卷积操作

importnumpyasnpimportos#朴素的卷积defconv_naive(x,w):N,H,W,Cx.shapeKh,Kw,_C,Kcw.shapeassert(C_

import numpy as npimport os# 朴素的卷积
def conv_naive(x, w):N,H,W,C &#61; x.shapeKh, Kw, _C, Kc &#61; w.shapeassert(C&#61;&#61;_C), (x.shape, w.shape)# stride is 1y&#61; np.zeros([N, H-Kh &#43;1, W-Kw&#43;1, Kc])for i0 in range(N):for i1 in range(H - Kh &#43; 1):for i2 in range(W - Kw &#43; 1):for i3 in range(Kh):for i4 in range(Kw):for i5 in range(C):for i6 in range(Kc):if i1 - i3 < 0 or i2 - i4 < 0 or i1 - i3 >&#61; H or i2 - i4 >&#61; W: continuey[i0, i1, i2, i6] &#43;&#61; x[i0, i1 &#43; i3, i2 &#43; i4, i5] * w[i3, i4, i5, i6]return y# %matplotlib inline
import pylab as pl
import PIL.Image as Image
import sys
import subprocess
img_path&#61;"cat.jpg"
if not os.path.isfile(img_path):cmd &#61; f"""wget -O - &#39;https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Felis_silvestris_catus_lying_on_rice_straw.jpg/220px-Felis_silvestris_catus_lying_on_rice_straw.jpg&#39; > {img_path}"""# subprocess.run(cmd)
im&#61;Image.open(img_path)
im.show()
img &#61; pl.imread(img_path)kernel &#61; np.array([[-1, -1, -1],[0, 0, 0],[1, 1, 1],
])
x &#61; img[np.newaxis,:,:,:1].astype("float32")
w &#61; kernel[:,:,np.newaxis,np.newaxis].astype("float32")y &#61; conv_naive(x, w)
print (x.shape, y.shape) # shape exists confusionimg &#61; Image.fromarray(y[0,:,:,:], mode&#61;&#39;RGB&#39;)
img.show()

输出&#xff1a;
(1, 147, 220, 1) (1, 145, 218, 1)
在这里插入图片描述


推荐阅读
author-avatar
Because_of_you龙
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有