我有一个python函数,它接受字符串s表达式,如"(add (Sub105) 5)",其中"add“和"sub”实际上是图像处理函数,并计算和创建字符串中表示的图像。图像处理函数接受常量、变量或其他图像(表示为向量列表),并返回以相同方式表示的图像。PIL用于将表示为向量列表的图像转换为图像文件。
为了计算前缀符号s-expression,我将s-expr转换为列表,反转它,并迭代标记,直到找到一个函数,此时将执行图像处理函数,生成的图像将替换列表中的函数及其参数。这样做,直到列表中只剩下一个元素,即最终图像。
问题是,如果我想为更复杂的表情制作大小合适的图像,我的计算机就会停止工作。这是否可以优化为使用更少的内存?
def createImage(self, sexpr, filename, (picWidth, picHeight)):
"""Use the image processing functions in ImgProcessing
to create an image from the procedural information
contained in the s-expression."""
img = Image.new("RGB",(picWidth,picHeight),(255,255,255))
ip = ImgProcessing(picWidth,picHeight)
# Split s-expression into list of tokens and reverse
sList = sexpr.replace("(","").replace(")","").split()
sList.reverse()
while len(sList) > 1:
for index,token in enumerate(sList):
# If token is an image processing function
if type(token) == str and self.FuncSet.has_key(token):
# If this function takes one argument
if self.FuncSet[token] == 1:
rawImage = eval("ip." + token + "(" + "\"" + str(sList[index-1]) +
"\"" + ")")
sList = sList[:index-1] + [rawImage] + sList[index+1:]
break
# If this function takes two arguments
elif self.FuncSet[token] == 2:
rawImage = eval("ip." + token + "(" + "\"" + str(sList[index-1]) +
"\"" + "," + "\"" + str(sList[index-2]) + "\"" +
")")
sList = sList[:index-2] + [rawImage] + sList[index+1:]
break
img.putdata(sList[0])
img.save(filename)发布于 2010-07-27 08:04:03
Profiling可以告诉你程序的大部分时间都花在哪里。
其次,str(sList[index-1])是否将Image转换为字符串?ip.token(...)是否返回图像?如果是这样,您将多次在string和Image之间进行转换。这可能会很慢。
改变一下可能会有所帮助。
rawImage = eval("ip." + token + "(" + "\"" + str(sList[index-1]) +
"\"" + ")")类似这样的东西
getattr(ip,token)(sList[index-1])当然,这取决于ip.token期望的参数类型。我在谷歌上找不到任何关于ImgProcessing的信息。这是一个自定义类吗?如果是这样,那么更多地解释它是如何工作的可能会有所帮助。如果ip.token可以从获取字符串更改为获取图像,这可能是一个很大的改进。
发布于 2010-07-27 08:33:56
根据我的经验,在一个大图像上用纯Python或PIL逐个像素执行的任何操作都会像一月份的糖蜜一样慢。考虑将低级内容转移到用C编写的Python扩展中。我使用过OpenCV,但这需要一些学习。
https://stackoverflow.com/questions/3339728
复制相似问题