图像最大池化

一. 最大池化

    池化:把图片使用均等大小网格分割,并求网格内代表值的操作

    最大池化:将网格中的最大值作为这个网格的代表值


二. 使用4*4网格对图像进行最大池化操作

import cv2

import numpy as np

# max pooling,G is the size of the window

def max_pooling(img, G=4):

    # Max Pooling

    out = img.copy()

    H, W, C = img.shape

    Nh = int(H / G)

    Nw = int(W / G)

    for y in range(Nh):

        for x in range(Nw):

            for c in range(C):

                out[G*y:G*(y+1), G*x:G*(x+1), c] = np.max(out[G*y:G*(y+1), G*x:G*(x+1), c])

    return out

# Read image

img = cv2.imread("../paojie.jpg")

# Max pooling

out = max_pooling(img)

# Save result

cv2.imwrite("out.jpg", out)

cv2.imshow("result", out)

cv2.waitKey(0)

cv2.destroyAllWindows()

 


三. 输出结果:


最大池化后图像

原图

四. 利用pytorch中MaxPool2d函数对图像进行最大池化

import cv2

import numpy as np

import torch

import torch.nn as nn

img = cv2.imread('../paojie.jpg',0)  #读入灰度图像

img = np.array(img,dtype='float32')

img = torch.from_numpy(img.reshape(1,1,img.shape[0],img.shape[1]))  # 将灰度图像转换为tensor

maxPool = nn.MaxPool2d(4)  #4*4的窗口,步长为4的最大池化

img = maxPool(img)

img = torch.squeeze(img)  #去掉1的维度

img = img.numpy().astype('uint8')  #转换格式,准备输出

cv2.imwrite("out.jpg", img)

cv2.imshow("result", img)

cv2.waitKey(0)

cv2.destroyAllWindows()

 


五. pytoch中MaxPool2d函数最大池化的输出结果


MaxPool2d输出结果

六. 参考内容

https://www.jianshu.com/p/2de998acee98

posted on 2020-03-15 12:53  我坚信阳光灿烂  阅读(1188)  评论(0编辑  收藏  举报

导航