码迷,mamicode.com
首页 > 其他好文 > 详细

图像平均池化 pytorch库中的平均池化

时间:2020-03-15 11:51:48      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:tps   strip   lin   ade   shu   结果   des   str   read   

一. 池化简介

    平均池化:将图片按照固定大小网格分割,网格内的像素值取网格内所有像素的平均值。

    池化:使用均等大小的网格将图片分割,并求网格内代表值的过程。

    池化是卷积神经网络(convolutional neural network)中非常重要的处理方式,能够有效地降低图像的维度。

    平均池化定义:

    技术图片


二. 将输入图像用4*4网格做平均池化

import cv2

import numpy as np

# average pooling

def average_pooling(img, G=4):

    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.mean(out[G*y:G*(y+1), G*x:G*(x+1), c]).astype(np.int)

 

    return out

# Read image

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

# Average Pooling

out = average_pooling(img)

# Save result

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

cv2.imshow("result", out)

cv2.waitKey(0)

cv2.destroyAllWindows()

 


三. 输出结果

技术图片
4*4平均池化结果
技术图片
原图

四. 深度学习中的平均池化操作,以pytorch库为例

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

avgPool = nn.AvgPool2d(4)  #4*4的窗口,步长为4的平均池化

img = avgPool(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()

 


五. pytorch中的平均池化输出结果( AvgPool2d() 函数 )

技术图片
AvgPool2d后结果

可以看到,pytorch中 AvgPool2d 函数,平均池化后降低了图像的维度。


六. 参考内容

https://www.jianshu.com/p/4a673069bc03

图像平均池化 pytorch库中的平均池化

标签:tps   strip   lin   ade   shu   结果   des   str   read   

原文地址:https://www.cnblogs.com/wojianxin/p/12496509.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!