解题思路
类似图像处理的平滑滤波。方法很菜,无话可说,实现都在注释了。
网络异常,图片无法展示
|
代码
# 661 class Solution(object): def imageSmoother(self, M): """ :type M: List[List[int]] :rtype: List[List[int]] """ #定义图片的高与宽 length_h,length_w = len(M),len(M[0]) #在给定图片的外围添加"_" ''' [['_', '_', '_', '_', '_'], ['_', 1, 1, 1, '_'], ['_', 1, 0, 1, '_'], ['_', 1, 1, 1, '_'], ['_', '_', '_', '_', '_']] ''' mask = [] for i in range(length_h + 2): if i in [0,length_h+1]: mask.append(["_"]*(length_w+2)) else: mask.append(["_"]+M[i - 1]+["_"]) #类似卷积定理通过滑窗求平均值 column = [] for i in range(length_h): row = [] for j in range(length_w): count,sum = 0,0 #count为计数,sum求子窗的和 cell = [mask[i][j], mask[i][j+1], mask[i][j+2], mask[i+1][j],mask[i+1][j+1],mask[i+1][j+2], mask[i+2][j],mask[i+2][j+1],mask[i+2][j+2]] #求出子窗的数列 for num in cell: #统计子窗平均值 if num in range(0,256): count += 1 sum += num mean = sum//count row.append(mean) column.append(row) return column