颜色反转优化 - Python Tkinter库

0 投票
1 回答
649 浏览
提问于 2025-04-17 04:13

今天我尝试用Tkinter库写一段Python代码,目的是反转一个.gif图片的颜色。代码运行得很好,正如我预期的那样,但在一个3.4ghz的处理器上运行大约需要50秒。我在想有什么办法可以让这个过程更快。基本上,我是逐个遍历图片中的每一个像素,获取颜色值,把它们转换成整数列表(这样方便进行数学运算),然后反转每个颜色值(新的颜色值 = 255 - 旧的颜色值),再把它们转换回字符串,以便PhotoImage的“put”方法可以处理并重写图片,最后显示反转后的图片。我想不出有什么可以改进的地方。我觉得逐个遍历每个像素肯定是导致慢的原因,但这个过程难道不是完全必要的吗?

from Tkinter import *
import tkMessageBox

class GUIFramework(Frame):
    def __init__(self, master=None):

    Frame.__init__(self, master)

    self.grid(padx=0, pady=0)
    self.btnDisplay = Button(self, text="Display!", command=self.Display)
    self.btnDisplay.grid(row=0, column=0)

    def Display(self):
        a = ''
        b = []
        self.imageDisplay = PhotoImage(file='C:\image.gif')
        for x in range(0, self.imageDisplay.width()):
            for y in range(0, self.imageDisplay.height()):
                value = self.imageDisplay.get(x,y)
                for i in value:
                    try:
                        c = int(i)
                        a += (i)
                    except:
                        b.append(int(a))
                        a = ''
                b.append(int(a))
                for i in range(0,3):
                    b[i] = (255 - b[i])
                self.imageDisplay.put('#%02x%02x%02x' %tuple(b), (x,y))
                b = []
                a = ''
        c = Canvas(self, width=700, height=700); c.pack()
        c.grid(padx=0,pady=0, column=0, row=0)
        c.create_image(0,0, image = self.imageDisplay, anchor = NW)

if __name__ == "__main__":
    guiFrame = GUIFramework()
    guiFrame.mainloop()

提前感谢你的帮助。

-Seth

1 个回答

4

试试这个:

def Display(self):
    self.imageDisplay = PhotoImage(file='C:\image.gif')
    for x in xrange(0, self.imageDisplay.width()):
        for y in xrange(0, self.imageDisplay.height()):
            raw = self.imageDisplay.get(x, y)
            rgb = tuple(255 - int(component) for component in raw.split())
            self.imageDisplay.put('#%02x%02x%02x' % rgb, (x, y))
    c = Canvas(self, width=700, height=700); c.pack()
    c.grid(padx=0,pady=0, column=0, row=0)
    c.create_image(0,0, image = self.imageDisplay, anchor = NW)

编辑: 这是新版本(更快,并且经过Justin Peel的优化)。

def Display(self):
    self.imageDisplay = PhotoImage(file='C:\image.gif')

    wrange = xrange(0, self.imageDisplay.width())
    hrange = xrange(0, self.imageDisplay.height())
    get = self.imageDisplay.get
    put = self.imageDisplay.put

    def convert_pixel(raw):
        return ('#%02x%02x%02x' %
            tuple(255 - int(component) for component in raw.split(' ')))

    for y in hrange:
        put('{' + ' '.join(convert_pixel(get(x, y)) for x in wrange) + '}', (0, y))

    c = Canvas(self, width=700, height=700);
    c.pack()
    c.grid(padx=0, pady=0, column=0, row=0)
    c.create_image(0, 0, image=self.imageDisplay, anchor=NW)

撰写回答