源码:
# 读取图片
img = cv2.imread("d:/img.jpg", 1)
height, width, channels = img.shape
# 灰度图
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 将图像分为8x8的多个小块,并统计小块每个像素的灰度值
# 划分灰度等级,例如0-255: 0-63, 64-127, ...
# 找出每个小块中,每个等级的个数,找出最多的
# 用最多的的平均值替换原像素
dst_img = np.zeros((height, width, channels), np.uint8)
for i in range(0, height):
for j in range(0, width):
max_level_arr = []
levelMap = {} # k: 级别, v: 原始像素值的列表
for m in range(-4, 4):
for n in range(-4, 4):
# 处理越界
if i + m >= height or i + m < 0:
m = -m
if j + n >= width or j + n < 0:
n = -n
# 划分等级 0-31, 32-63, ...
level = gray_img[i + m, j + n] // 32
if not level in levelMap.keys():
levelMap[level] = [img[i + m, j + n],]
else:
levelMap[level].append(img[i + m, j + n])
# 个数最多的级别
if len(levelMap[level]) > len(max_level_arr):
max_level_arr = levelMap[level]
# 取均值
size = len(max_level_arr)
b_sum, g_sum, r_sum = 0, 0, 0
for b, g, r in max_level_arr:
b_sum += b
g_sum += g
r_sum += r
dst_img[i, j] = [b_sum // size, g_sum // size, r_sum // size ]
cv2.imshow("dst_img", dst_img)
if cv2.waitKey() == ord("q"):
cv2.destroyAllWindows()
效果: