fork download
  1. def get_pixel_at(pixel_grid, i, j):
  2. '''
  3. Returns the pixel in pixel_grid at row i and column j (zero-indexed).
  4. Returns 0 if i or j is out of bounds for the given pixel_grid.
  5. '''
  6. if i>=0 and j>=0:
  7. if i<len(pixel_grid) and j<len(pixel_grid[i]):
  8. return pixel_grid[i][j]
  9. else:
  10. return 0
  11. else:
  12. return 0
  13.  
  14. def average_of_surrounding(pixel_grid, i, j):
  15. '''
  16. Returns the unweighted average of the values of the pixel at row i
  17. and column j and the eight pixels surrounding it.
  18. '''
  19. pixel_sum = 0
  20. for r in [i-1, i, i+1]:
  21. for c in [j-1, j, j+1]:
  22. pixel_sum=pixel_sum+get_pixel_at(pixel_grid, r, c)
  23. # pixel_sum should be an integer. We intend for this to be
  24. # truncating integer division.
  25. return pixel_sum / 9
  26.  
  27. def blur(pixel_grid):
  28. '''
  29. Given pixel_grid (a grid of pixels), returns a new grid of pixels
  30. that is the result of blurring pixel_grid. In the output grid,
  31. each pixel is the average of that pixel and its eight neighbors in
  32. the input grid.
  33. '''
  34.  
  35. new_grid=pixel_grid
  36. for r in range(0, len(pixel_grid)):
  37. for c in range(0, len(pixel_grid[r])):
  38. new_grid[r][c]=average_of_surrounding(pixel_grid, r, c)
  39. return new_grid
  40.  
  41. def test_average_of_surrounding():
  42. test_grid = [
  43. [1, 2, 3],
  44. [4, 5, 6],
  45. [7, 8, 9]
  46. ]
  47.  
  48. print blur(test_grid)
  49. test_average_of_surrounding()
Success #stdin #stdout 0.01s 7212KB
stdin
Standard input is empty
stdout
[[1, 2, 1], [3, 4, 3], [2, 3, 2]]