Hi, I'm Ramu. This time, we will implement Max pooling, which uses the maximum value in the area as a representative value, among the pooling processes that divide the image into grids.
Pooling, which was explained last time, is a process that divides an image into a fixed-length area and makes all the values in that area into a certain value. By applying this processing, the image becomes a mosaic. Max pooling fills the area with the maximum pixel value in the area. The only difference between average pooling and Max pooling is whether to use the average value or the maximum value.
maxPooling.py
import numpy as np
import cv2
import matplotlib.pyplot as plt
def maxPooling(img,k):
dst = img.copy()
w,h,c = img.shape
#Length from the center pixel to both ends pixels
size = k // 2
#Pooling process
for x in range(size, w, k):
for y in range(size, h, k):
dst[x-size:x+size,y-size:y+size,0] = np.max(img[x-size:x+size,y-size:y+size,0])
dst[x-size:x+size,y-size:y+size,1] = np.max(img[x-size:x+size,y-size:y+size,1])
dst[x-size:x+size,y-size:y+size,2] = np.max(img[x-size:x+size,y-size:y+size,2])
return dst
#Image reading
img = cv2.imread('image.jpg')
#Max pooling
#The second argument is the area length
img = maxPooling(img,40)
#Save image
cv2.imwrite('result.jpg', img)
#Image display
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
The left image is the input image, the center of the image is the previous average pooling, and the right image is the output image this time. You can see that the image looks like a mosaic. Also, the entire image is brighter than the average pooling because it uses the maximum brightness.
If you have any questions, please feel free to contact us. imori_imori's Github has the official answer, so please check that as well. .. Also, since python is a beginner, please kindly point out any mistakes.
Recommended Posts