zoukankan      html  css  js  c++  java
  • leetcode 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:

      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].

        不修改M:

    class Solution(object):
        def imageSmoother(self, M):
            """
            :type M: List[List[int]]
            :rtype: List[List[int]]
            """
            row = len(M)
            col = len(M[0])
            R = [[0 for i in range(col)] for j in range(row)]
            
            def get_avg(M, i, j):
                diff_pos = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
                s = M[i][j]
                l = 1           
                for x,y in diff_pos:
                    if 0<=i+x<row and 0<=j+y<col:
                        s += M[i+x][j+y]
                        l += 1            
                return s//l
            
            for i in xrange(0, row):
                for j in xrange(0, col):
                    R[i][j] = get_avg(M, i, j)
            return R

    修改M:

    class Solution(object):
        def imageSmoother(self, M):
            """
            :type M: List[List[int]]
            :rtype: List[List[int]]
            """
            row = len(M)
            col = len(M[0])
                    
            def get_avg(M, i, j):
                s = l = 0          
                for x in xrange(-1, 2):
                    for y in xrange(-1, 2):
                        if 0<=i+x<row and 0<=j+y<col:
                            s += (M[i+x][j+y] & 0xff)
                            l += 1            
                return (s//l) <<8
            
            for i in xrange(0, row):
                for j in xrange(0, col):
                    M[i][j] += get_avg(M, i, j)
            
            for i in xrange(0, row):
                for j in xrange(0, col):
                    M[i][j] >>= 8
            return M

    记得细节:M[i][j] += get_avg(M, i, j) 是+= 而非=

  • 相关阅读:
    移动安全
    Photoshop笔记
    ARMv7 与 ARMv8对比
    centos系统 网络配置
    视频大文件压缩
    开发者必备Linux命令
    开发者必备Docker命令
    文件服务器minio
    Java 图片Base64
    socket
  • 原文地址:https://www.cnblogs.com/bonelee/p/8689135.html
Copyright © 2011-2022 走看看