挑战图像处理100问(7)——平均池化

在这里插入图片描述
读取图像,对图像作平均池化处理。
原图如下:

在这里插入图片描述

关于平均池化

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

我们将这种把图片使用均等大小网格分割,并求网格内代表值的操作称为池化(Pooling)

池化操作是 卷积神经网络(Convolutional Neural Network) 中重要的图像处理方式。平均池化按照下式定义:
v = 1 R   i = 1 R   v i v=\frac{1}{|R|}\ \sum\limits_{i=1}^R\ v_i

这个题实现起来也很简单!

代码实现
# -*- coding: utf-8 -*-
"""
Created on Wed Apr  8 20:56:10 2020

@author: Tian YJ
"""


import cv2
import numpy as np

# 定义平均池化函数,网格大小设为8*8
def average_pooling(img, G=8):
	out = img.copy()
	#获取图片尺寸
	H, W, C = img.shape
	H_new = int(H/G)
	W_new = int(W/G)

	for h in range(H_new):
		for w in range(W_new):
			for c in range(C):
				out[G*h:G*(h+1), G*w:G*(w+1), c] = np.mean(img[G*h:G*(h+1), G*w:G*(w+1), c]).astype(np.int)
	return out

# 读取图片
path = 'C:/Users/86187/Desktop/image/'


file_in = path + 'cake.jpg' 
file_out = path + 'average_pooling.jpg' 
img = cv2.imread(file_in)

# 调用函数进行平均池化
out = average_pooling(img)

# 保存图片
cv2.imwrite(file_out, out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果展示
原图 平均池化
在这里插入图片描述 在这里插入图片描述
发布了43 篇原创文章 · 获赞 40 · 访问量 2110

猜你喜欢

转载自blog.csdn.net/qq_42662568/article/details/105396873