Hi, I'm Ramu. This time, even in the pooling process, which is a method of dividing the image into grids, we will implement the average pooling with the average value in the area as the representative value.
Pooling is the process of dividing an image into a fixed-length area and making all the values in that area a certain value. By applying this processing, the image becomes a mosaic. In average pooling, the area is filled with the average pixel value in the area.
Average pooling is defined by the following formula:
R is an area, for example, if it is an area of 8 x 8 pixels
v = \frac{1}{|R|}\sum_{i \in R}v_i
avePooling.py
import numpy as np
import cv2
import matplotlib.pyplot as plt
def avePooling(img,k):
dst = img.copy()
w,h,c = img.shape
#Length from the center pixel to both ends pixels
size = k // 2
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.mean(img[x-size:x+size,y-size:y+size,0])
dst[x-size:x+size,y-size:y+size,1] = np.mean(img[x-size:x+size,y-size:y+size,1])
dst[x-size:x+size,y-size:y+size,2] = np.mean(img[x-size:x+size,y-size:y+size,2])
return dst
#Image reading
img = cv2.imread('image.jpg')
#Average pooling
#k is the area size
img = avePooling(img,40)
#Save image
cv2.imwrite('result.jpg', img)
#Image display
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
The image on the left is the input image, and the image on the right is the output image. You can see that the image looks like a mosaic. It looks like sashimi, but it's sashimi.
The full version of Lena's image, which is often used in image processing, can also be posted on Qiita if average pooling processing is applied.
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