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

    技术2022-07-11  83

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

    导读

    加载图片展示图像复制图像创建一个卷积卷积操作展示卷积结果最大池化----(2,2)

    加载图片

    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() #图像的特征得到保留,从坐标轴上来看,图片大小变成了原来的一半

    Processed: 0.016, SQL: 9