吴恩达团队 Tensorflow课程学习笔记 4

本节的内容主要是了解一下卷积操作的过程,卷积操作在Tensorflow已经封装好了,可以直接使用的

加载图片

import cv2
import numpy as np
from scipy import misc
i = misc.ascent() #返回一张图像

展示图像

import matplotlib.pyplot as plt
plt.grid(False)
plt.gray()
plt.axis('off')
plt.imshow(i)
plt.show()

在这里插入图片描述

复制图像

i_transformed = np.copy(i)

#创建变量来监控x,y的维度
size_x = i_transformed.shape[0] 
size_y = i_transformed.shape[1]

#查看维度
print(size_x)
print(size_y)
#它是一幅512*512的图像

创建一个卷积

形式为3*3的数组

filter = [ [0, 1, 0], [1, -4, 1], [0, 1, 0]]
filter = [ [-1, -2, -1], [0, 0, 0], [1, 2, 1]]#检测垂直线
#filter = [ [-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]#检测水平线
weight  = 1

这里的weight没太懂

If all the digits in the filter don't add up to 0 or 1, you 
should probably do a weight to get it to do so
# so, for example, if your weights are 1,1,1 1,2,1 1,1,1
# They add up to 10, so you would set a weight of .1 if you want to normalize them

卷积操作

遍历整张图像,留下一个像素的边距

for x in range(1,size_x-1): #循环从1开始(不是0),最终图像大小会变成(x-1) *(y-1)
  for y in range(1,size_y-1):
      convolution = 0.0
      convolution = convolution + (i[x - 1, y-1] * filter[0][0])
      convolution = convolution + (i[x, y-1] * filter[0][1])
      convolution = convolution + (i[x + 1, y-1] * filter[0][2])
      convolution = convolution + (i[x-1, y] * filter[1][0])
      convolution = convolution + (i[x, y] * filter[1][1])
      convolution = convolution + (i[x+1, y] * filter[1][2])
      convolution = convolution + (i[x-1, y+1] * filter[2][0])
      convolution = convolution + (i[x, y+1] * filter[2][1])
      convolution = convolution + (i[x+1, y+1] * filter[2][2])
      convolution = convolution * weight #确保结果在0-255间
      if(convolution<0):
        convolution=0
      if(convolution>255):
        convolution=255
      i_transformed[x, y] = convolution #load the new value into the transformed image

这里图像的像素位置与卷积核的对应位置怎么感觉有出入??

展示卷积结果

注意卷积之后的图像大小还是512*512

plt.gray()
plt.grid(False)
plt.imshow(i_transformed)
#plt.axis('off')
plt.show()   

第一个卷积核的结果
在这里插入图片描述
第二个卷积核的结果
在这里插入图片描述
第三个卷积核的结果
在这里插入图片描述

最大池化----(2,2)

new_x = int(size_x/2)
new_y = int(size_y/2)
newImage = np.zeros((new_x, new_y))
for x in range(0, size_x, 2):
  for y in range(0, size_y, 2):
    pixels = []
    pixels.append(i_transformed[x, y])
    pixels.append(i_transformed[x+1, y])
    pixels.append(i_transformed[x, y+1])
    pixels.append(i_transformed[x+1, y+1])
    newImage[int(x/2),int(y/2)] = max(pixels)

# Plot the image. Note the size of the axes -- now 256 pixels instead of 512
plt.gray()
plt.grid(False)
plt.imshow(newImage)
#plt.axis('off')
plt.show()      
    
#图像的特征得到保留,从坐标轴上来看,图片大小变成了原来的一半

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值