图像最大池化

一. 最大池化

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

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


二. 使用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   我坚信阳光灿烂  阅读(1271)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示