- 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
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
Notice
1.The value in the given matrix is in the range of [0, 255].
2.The length and width of the given matrix are in the range of [1, 150].
解法1:
代码如下:
class Solution {
public:
/**
* @param M: a 2D integer matrix
* @return: a 2D integer matrix
*/
vector<vector<int>> imageSmoother(vector<vector<int>> &M) {
int rowSize = M.size();
if (rowSize == 0) return {};
int colSize = M[0].size();
if (colSize == 0) return {};
vector<vector<int>> M2(rowSize, vector<int>(colSize));
vector<int> dx = {-1, -1, 1, 1, 0, 0, 1, -1};
vector<int> dy = {-1, 1, -1, 1, -1, 1, 0, 0};
for (int i = 0; i < rowSize; ++i) {
for (int j = 0; j < colSize; ++j) {
int sum = M[i][j];
int count = 1; //remember to count itself
for (int k = 0; k < 8; ++k) {
int newX = i + dx[k];
int newY = j + dy[k];
if (newX >= 0 && newX < rowSize && newY >= 0 && newY < colSize) {
count++;
sum += M[newX][newY];
}
}
M2[i][j] = sum / count;
}
}
return M2;
}
};
可用以下循环遍历9个点。
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (x + i < 0 || x + i >= nx || y + j < 0 || y + j >= ny) {
continue;
}
本文详细介绍了如何设计一种图像平滑算法,该算法能够将图像中每个像素的灰度值调整为周围8个像素和自身平均灰度值的向下取整结果。通过具体的示例和代码实现,展示了算法的工作原理和效果。
429

被折叠的 条评论
为什么被折叠?



