leetcode 661. Image Smoother(图片平滑)

该博客介绍了一种图像平滑算法,通过计算每个像素与其8邻域的平均值并向下取整来实现。给定一个二维整数矩阵表示图像的灰度,程序遍历每个像素,考虑边界条件,使用Java实现。平滑后的矩阵每个元素是周围像素的平均值(包括自身),并使用Math.floor进行取整。
摘要由CSDN通过智能技术生成

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

图片平滑,每个像素求它和它8邻域的平均值取floor,也就是向下取整

思路:
直接暴力解决,但是注意边界条件
而且注意java的floor函数返回是double,要down cast

    public int[][] imageSmoother(int[][] M) {
        if(M == null || M.length == 0) {
            return new int[1][1];
        }
        int m = M.length;
        int n = M[0].length;
        int[][] result = new int[m][n];
        
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                int up = (i == 0) ? i : i-1;
                int down = (i == m-1) ? i : i+1;
                int left = (j == 0) ? j : j-1;
                int right = (j == n-1) ? j : j+1;
                result[i][j] = smoother(M, up, down, left, right);
            }
        }
        
        return result;
    }
    
    int smoother(int[][] M, int up, int down, int left, int right) {
        float tmp = 0f;
        int count = 0;
        
        for(int i = up; i <= down; i++) {
            for(int j = left; j <= right; j++) {
                tmp += M[i][j];
                count ++;
            }
        }
        return (int)Math.floor(tmp/count);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值