Advertisement
Guest User

Basics of parallel flood fill

a guest
Oct 15th, 2014
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. import Image
  2.  
  3. def randomSeedFill(imageFileName, n_centers = 256 ):
  4.  
  5.     origImage = Image.open(imageFileName)
  6.     w, h = origImage.size
  7.  
  8.     centers = [ (random.randint(0, w-1), random.randint(0, h-1)) for i in xrange(n_centers) ]
  9.     colors = [origImage.getpixel(cen) for cen in centers]
  10.  
  11.     im = multiFloodFillQShuffle(w, h, centers, colors)
  12.  
  13.     outFilename = "randomSeedFill shuffle - %s - n_centers %d.png" % (imageFileName.split(".")[0], n_centers)
  14.     out = open(outFilename, 'wb')
  15.     im.save(out, "PNG")
  16.     out.close()
  17.  
  18. # "Parallel" queue-based flood fill. Shuffles the order neighbors are visited.
  19. def multiFloodFillQShuffle( w, h, pixelAddresses, replacementColors ):
  20.  
  21.  
  22.     im = Image.new("RGB", (w, h))
  23.    
  24.     # keeps track of which pixels have been filled
  25.     processed = {}
  26.     for x in xrange(w):
  27.         for y in xrange(h):
  28.             processed[(x, y)] = False
  29.            
  30.     # each seed gets its own queue
  31.     qs = [[p] for p in pixelAddresses]
  32.  
  33.     sanity = 0
  34.     while sum([len(q) for q in qs]) > 0:
  35.  
  36.         # while loops make me nervous...
  37.         sanity += 1
  38.         if sanity > w*h:
  39.             print "insanity"
  40.             break
  41.  
  42.         for i in xrange(len(qs)):
  43.  
  44.             q = qs[i]
  45.             if len(q) == 0:
  46.                 continue
  47.             replacementColor = replacementColors[i]
  48.             x, y = q.pop()
  49.             x = x%w
  50.             y = y%h
  51.  
  52.             if not processed[(x, y)]:
  53.  
  54.                 im.putpixel((x, y), replacementColor)
  55.                 processed[(x, y)] = True
  56.                
  57.                 xp = (x+1)%w; xm = (x-1)%w; yp = (y+1)%h; ym = (y-1)%h
  58.                 neighbors = [(xm, y), (x, ym), (x, yp), (xp, y)]
  59.  
  60.                 # shuffle the directions then add each neighbor to the queue
  61.                 # (or don't shuffle to get a striped effect)
  62.                 # (or cycle through through them for a pattern, or...)
  63.                 random.shuffle(neighbors)
  64.                 for n in neighbors:
  65.                     if not processed[n]:
  66.                         q.append(n)
  67.  
  68.     return im
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement