Advertisement
999ms

Untitled

Mar 31st, 2020
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. from PIL import Image, ImageFilter
  2. try:  
  3.     im = Image.open("C:\\Users\\bossb\\Desktop\\21.png")  
  4. except FileNotFoundError:  
  5.     print("Файл не найден")
  6.    
  7. im = im.convert('RGB')
  8. w, h = im.size
  9.  
  10. img = im
  11. im = im.load()
  12.  
  13. p = [[(i, j) for j in range(h)] for i in range(w)]
  14. d = [[1 for j in range(h)] for i in range(w)]
  15.  
  16. def get(x, y):
  17.     if p[x][y] == (x, y):
  18.         return (x, y)
  19.     p[x][y] = get(p[x][y][0], p[x][y][1])
  20.     return p[x][y]
  21.  
  22. def uni(a, b):
  23.     a = get(a[0], a[1])
  24.     b = get(b[0], b[1])
  25.     if a == b:
  26.         return
  27.     if d[a[0]][a[1]] < d[b[0]][b[1]]:
  28.         a, b = b, a
  29.     p[b[0]][b[1]] = a
  30.     d[a[0]][a[1]] += d[b[0]][b[1]]
  31.  
  32.  
  33. def areConnected(a, b):
  34.     return abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) < 15
  35.  
  36. for x in range(w):
  37.     for y in range(h):
  38.         for dx in range(2):
  39.             for dy in range(2):
  40.                 if dx == 0 and dy == 0:
  41.                     continue
  42.                 nx = x + dx
  43.                 ny = y + dy
  44.                 if nx < 0 or ny < 0 or nx >= w or ny >= h:
  45.                     continue
  46.                 if areConnected(im[x, y], im[nx, ny]):
  47.                     uni((x, y), (nx, ny))
  48.                    
  49.  
  50. mp = {}
  51.  
  52. for x in range(w):
  53.     for y in range(h):
  54.         par = get(x, y)
  55.         if par not in mp:
  56.             mp[par] = 0
  57.         mp[par] += 1
  58.        
  59. sz = w * h
  60. for value in mp:
  61.     cnt = mp[value]
  62.     x = int(255.0 * cnt / sz)
  63.     if x > 100:
  64.         x = 255
  65.     else:
  66.         x = 0
  67.     if cnt < 3:
  68.         x = 255
  69.     mp[value] = (x, x, x)
  70.    
  71.  
  72.        
  73.    
  74. for x in range(w):
  75.     for y in range(h):
  76.         im[x, y] = mp[get(x, y)]
  77.  
  78. img.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement