Advertisement
milanmetal

[Python] Average color over kernel-sized position on image

Mar 2nd, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. from PIL import Image
  2.  
  3. # PIL accesses images in Cartesian co-ordinates, so it is Image[columns, rows]
  4. # img = Image.new( 'RGB', (1280, 720), "black") # create a new black image
  5. #img = Image.open("rsz_2lemibrat.jpg")
  6. img = Image.open("lena.jpg")
  7. pixels = img.load() # create the pixel map
  8.  
  9. # https://stackoverflow.com/questions/6667201/how-to-define-a-two-dimensional-array-in-python
  10. # Creates a list containing 32 lists, each of 32 items, all set to 0
  11. k_w, k_h = 40, 40
  12. x_pos, y_pos = 200, 250
  13. k_i, k_j = 0, 0
  14.  
  15. kernel = {}
  16. # kernel = [[0 for x in range(w)] for y in range(h)]
  17.  
  18. print(img.size)     # Prints (250, 250)
  19.  
  20. #for i in range(img.size[0]):    # for every col:
  21.     #for j in range(img.size[1]):    # For every row
  22.         #pixels[i,j] = (i, j, 100) # set the colour accordingly
  23.         # print(pixels[i,j][0])
  24.  
  25. for i in range(x_pos, x_pos + k_w):
  26.     for j in range (y_pos, y_pos + k_h):
  27.         kernel[k_i, k_j] = pixels[i, j]
  28.  
  29.         k_j += 1
  30.         print('k_j = ' + str(k_j) + ' a vrednost RGB = ' + str(pixels[i, j]))
  31.         if k_j == k_h:
  32.             k_j = 0
  33.  
  34.     k_i += 1
  35.     print('k_i = ' + str(k_i) + ' a vrednost RGB = ' + str(pixels[i, j]))
  36.     if k_i == k_w:
  37.         k_i = 0
  38.  
  39.  
  40. #print('Trenutno ispisujem: ' + str(kernel[22,23]))
  41. k_R, k_G, k_B = 0, 0, 0
  42. for i in range(0, k_w):
  43.     for j in range (0, k_h):
  44.         k_R += kernel[i, j][0]
  45.         k_G += kernel[i, j][1]
  46.         k_B += kernel[i, j][2]
  47.         #print(kernel[i, j])
  48.  
  49. # Hehe, nisi dovoljno mocan ako ne mozes ovo ha ha ha
  50. # k_R, k_G, k_B /= 32, 32, 32
  51. k_R /= k_w * k_h
  52. k_G /= k_w * k_h
  53. k_B /= k_w * k_h
  54. print('Srednja vrijednost: R = ' + str(k_R) + ' G = ' + str(k_G) + ' B = ' + str(k_B))
  55.  
  56.  
  57. for i in range(x_pos, x_pos + k_w):
  58.     for j in range (y_pos, y_pos + k_h):
  59.         pixels[i, j] = (k_R, k_G, k_B)
  60.  
  61. img.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement