使用旋转掩码的平滑
算法:使用旋转掩膜的平均
1.考虑图像的每个像素(i,j).
2.根据(5.29)式计算像素(i,j)所有可能的旋转掩膜的散布.
3.选择具有最小散布的掩膜.
4.将所选掩膜内的平均亮度赋给输出图像中的像素(i,j).
实现前后对比:
实现代码:
import cv2 import numpy as np class rotate_mask(): def __init__(self, img_path, size): ''' img: 待处理的图片 size: 掩码的大小(奇数) ''' self.img = cv2.imread(img_path, 0) self.size = size self.h, self.w = self.img.shape self.new = np.zeros((self.h, self.w), np.uint8) def mask_location(self, x, y): ''' 任一图像位置的所有掩码位置区域 ''' location_list = [(x, x+2, y, y+2), (x-1, x+1, y, y+2), (x-2, x, y, y+2), (x-2, x, y-1, y+1), (x-2, x, y-2, y), (x-1, x+1, y-2, y), (x, x+2, y-2, y), (x, x+2, y-1, y+1), (x-1, x+1, y-1, y+1)] return location_list def spreading_value(self, r): ''' 计算任一掩码的散步值 r代表任一掩码的区域 ''' a = 0 b = 0 i1, i2, j1, j2 = r for i in range(i1, i2+1): for j in range(j1, j2+1): a += self.img[i, j] ** 2 b += self.img[i, j] n = (i2-i1+1) * (j2-j1+1) value = 1/n * (a-(b**2/n)) return (value, b, n) def min_mask(self, x, y): ''' 计算出任一图像位置的最小散布值对应的掩码区域在原图片中的平均亮度值 x, y为任一位置的坐标 ''' spreading_value_list = [] for i in self.mask_location(x, y): spreading_value_list.append(self.spreading_value(i)) min_value, n = sorted(spreading_value_list, key=lambda x:x[0])[0][1:] average_value = int(min_value/n) return average_value def main(self): ''' 具备最多掩码的区域,即需要从num开始遍历 ''' num = self.size // 2 + 1 for i in range(num, self.h-num): for j in range(num, self.w-num): self.new[i, j] = self.min_mask(i, j) cv2.imshow('new', self.new) cv2.imwrite('5.jpg', self.new) cv2.waitKey() cv2.destroyAllWindows() r = rotate_mask('./1.jpg', 3) r.main()
后记:有没有发现实现之后的图片外延有一圈黑线,因为未作处理,后续会更新