2014-01-22 47 views
1

我有一个二进制图像(见下文),我想标记中心大斑点内的所有点为1(白色)。如果我理解正确,最好的方法是使用洪水填充算法;有没有你建议使用的Python模块?如果不是,你将如何构建脚本?洪水在二进制图像中填充形状

谢谢!

The image I am working with

+0

有几个实现[此处](http://en.wikipedia.org/wiki/Flood_fill#The_algorithm)。我可以告诉你,从经验来看,基于幼稚堆栈的递归方法效率不高...... – will

+0

谢谢!你认为哪种方法最好? –

+0

这是相当强烈的执行依赖。这将是一个非常好的问题,要求一个类的艾莫,至少如果你不能很容易地在网上得到答案...... [这里](http://www.codeproject.com/Articles/6017/QuickFill-一个高效的洪水填充算法)是你可以使用的各种方法的很好的描述。 – will

回答

1

在这里,这是洪水填充非常幼稚的做法(使用你的问题YOUT 0和1的尽可能详细,但不读取图像,但硬编码数据)环游在python缺乏TCO的。也许可以给你一些建议:

#! /usr/bin/python3 

d = '''111110001111101 
110000011100000 
111000010111001 
111100100111111 
111100000111111 
111110111111111''' 

def flood(grid, x, y): 
    toBeFilled = {(x, y)} 
    while toBeFilled: 
     tbf = set() 
     for x, y in toBeFilled: 
      try: 
       if grid[y][x]: continue #Pixel is already 1 -> no action 
      except IndexError: continue #Index is out of bounds 
      grid[y][x] = 1 #set Pixel to white 
      for xoff, yoff in ((1, -1), (1, 0), (1, 1), (0, -1), (0, 1), (-1, -1), (-1, 0), (-1, 1)): 
       tbf |= {(x + xoff, y + yoff)} #add adjacent pixels 
     toBeFilled = tbf 

def pprint(grid): 
    print('-' * 20) 
    for line in grid: print(''.join(str(i) for i in line)) 
    print('-' * 20) 

d = [[int(c) for c in line] for line in d.split('\n')] 
pprint(d) 
flood(d, 4, 1) 
pprint(d) 

输出是:

-------------------- 
111110001111101 
110000011100000 
111000010111001 
111100100111111 
111100000111111 
111110111111111 
-------------------- 
-------------------- 
111111111111101 
111111111100000 
111111111111001 
111111111111111 
111111111111111 
111111111111111 
--------------------