每日一题-图片平滑器

661. 图片平滑器

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/image-smoother

题目描述

图像平滑器 是大小为3 x 3 的过滤器,用于对图像的每个单元格平滑处理,平滑处理后单元格的值为该单元格的平均灰度。

每个单元格的平均灰度定义为:该单元格自身及其周围的 8 个单元格的平均值,结果需向下取整。(即,需要计算蓝色平滑器中 9 个单元格的平均值)。

如果一个单元格周围存在单元格缺失的情况,则计算平均灰度时不考虑缺失的单元格(即,需要计算红色平滑器中 4 个单元格的平均值)。

思路

直接模拟,遍历求3 x 3平滑框内像素值与像素个数。用两个数组dx,dy表示平滑框大小。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int dx[3] = {-1,0,1};
int dy[3] = {-1,0,1};
vector<vector<int>> imageSmoother(vector<vector<int>>& img) {
int m = img.size();
int n = img[0].size();
vector<vector<int>> new_img(m,vector<int> (n));
for (int i = 0 ; i < m ; ++i) {
for (int j = 0 ; j < n ; ++j) {
int value = 0;
int num = 0;
for (int x:dx) {
for (int y:dy) {
if (i+x >= 0 && i+x < m && j+y >= 0 && j+y < n) {
value += img[i+x][j+y];
++num;
}
}
}
new_img[i][j] = value/num;
}
}
return new_img;
}
}
;