0

My objective is to create a function named findList() which holds the given parameter of a point and the screen surface.

My aim is to calculate the colour of that point then return a list of the filled colour.

In example, if one had a screen with a red circle in it and the point was inside the red circle, I would like to be able to return a list holding all the points of that circle.

Basically, the point expands, avoiding all other colours and the edge of the screen until it can expand no further; in which then the function returns the list of all the created points.

Here's what I tried:

def findList(point,screen):
    directions=[(0,0)]
    myList=[]
    myList.append(point)
    startColour=screen.get_at(point)
    i=0
    loop=0
    while True:
        loop=loop+1
        print(loop)
        directions=[]
        print("Length of myList: "+str(len(myList)))
        for i in range(len(myList)):
            if myList[i][0]+1<WINDOWWIDTH and screen.get_at((myList[i][0]+1,myList[i [1]))==startColour and myList[i][0]+1 not in myList and myList[i][0]+1 not in directions:
                directions.append((myList[i][0]+1,myList[i][1]))
            if myList[i][0]-1>0 and screen.get_at((myList[i][0]-1,myList[i][1]))==startColour and myList[i][0]-1 not in myList and myList[i][0]-1 not in directions:
                directions.append((myList[i][0]-1,myList[i][1]))
            if myList[i][1]+1<WINDOWHEIGHT and screen.get_at((myList[i][0],myList[i][1]+1))==startColour and myList[i][1]+1 not in myList and myList[i][1]+1 not in directions:
                directions.append((myList[i][0],myList[i][1]+1))
            if myList[i][1]-1>0 and screen.get_at((myList[i][0],myList[i][1]-1))==startColour and myList[i][1]-1 not in myList and myList[i][1]-1 not in directions:
                directions.append((myList[i][0],myList[i][1]-1))

        print(len(directions))
        for i in directions:
            myList.append(i)
        if len(directions)==0:
            break
    print("Exited loop.")
    return myList

I know the coding style is terrible and much of it is probably useless but the general problem is that the function(probably) works but is painstakingly slow and seems to add previously added pixels a lot until my poor little netbook can no longer cope with the 100 000 points it is working with.

It would really help me with my program if someone could make some suggestions for a better function because, being only 13, I am horribly confused with this messy bit of code (note the 4 conditions in the ifs).

4

1 回答 1

0

从本质上讲,您要的是“Flood-Fill”算法的第一部分,这是 Microsoft Paint 等程序用来用新颜色填充区域的程序。该算法首先找到所有相同颜色的连接像素,然后改变它们的颜色。查看wikipedia 页面或此stackoverflow 问题以了解 python 实现。

至于您的代码,有几件事可以改进。我会建议:

  1. 使用 aset()而不是列表。这样您就不必处理重复的点
  2. 仅使用if/elif子句而不是ifs。这将减少计算时间。
  3. 您的if陈述非常复杂但非常多余。您可能想尝试将它们分解为一组嵌套的if/elif语句。

寻找 Flood-Fill 算法并尝试重写你所拥有的。查看其他一些示例可能会帮助您显着简化代码。

于 2013-08-02T14:52:17.933 回答