661. Image Smoother
Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.
Example 1:
Input: [[1,1,1], [1,0,1], [1,1,1]] Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] Explanation: For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 For the point (1,1): floor(8/9) = floor(0.88888889) = 0
Note:
- The value in the given matrix is in the range of [0, 255].
- The length and width of the given matrix are in the range of [1, 150].
题意:给定二维矩阵,表示图像的灰度。对图像进行平滑处理,将每一个像素的值换成其周围9个单元格的平均值。
思路
1.题目要求矩阵中元素周围一圈元素和它本身累加之后求平均值。
2.因为对于每个元素,计算之后的值覆盖原值会影响其他元素的计算,所以要创建一个新的二维数组来保存。
3.比较老实(呆)的计算M[i][j]的方式:M[i-1][n-1]+M[i-1][n]+M[i-1][n+1]+...+M[i+1][n+1],再来求平均。再来判断元素是在四个角上还是边上还是内部的,这样做太麻烦了。
4.现在需要一个比较好的方式来指代M[i][j]的周围元素和其本身。假设M[i+m][j+n]是周围元素和其本身元素中的一个,那么m和n属于[-1, 0, 1]。所以可以建两个数组:
1 public int[][] imageSmoother(int[][] M) { 2 if (M == null) { 3 return null; 4 } 5 int rows = M.length; 6 if (rows == 0) { 7 return new int[0][]; 8 } 9 10 int cols = M[0].length; 11 int[][] rets = new int[rows][cols]; 12 for (int row = 0; row < rows; row++) { 13 for (int col = 0; col < cols; col++) { 14 int count = 0; 15 int sum = 0; 16 for (int incR : new int[]{-1, 0, 1}) { 17 for (int incC : new int[]{-1, 0, 1}) { 18 int r = row + incR; 19 int c = col + incC; 20 if (0 <= r && r < rows && 0 <= c && c < cols) { 21 count++; 22 sum += M[r][c]; 23 } 24 } 25 } 26 rets[row][col] = sum / count; 27 } 28 } 29 return rets; 30 }