首页 > 解决方案 > 用于锐化图像的 Python 项目

问题描述

所以,我让我的朋友帮我处理这个 python 项目,它在他的电脑上运行,但是当我回到家并试图在我的电脑上运行它时,我得到了一系列错误代码,(我会发布我得到的所有错误代码下方)。所以这个项目应该采用 Smokey.gif 文件,并对其进行锐化,然后在单独的窗口中显示新锐化的图像。该项目有 2 个模块,image.py 模块和锐化模块。

这是代码:

image.py 的代码:

  import tkinter
 import os, os.path

tk = tkinter

_root = None


class ImageView(tk.Canvas):
def __init__(self, image,
             title="New Image",
             autoflush=False):
    master = tk.Toplevel(_root)
    master.protocol("WM_DELETE_WINDOW", self.close)
    tk.Canvas.__init__(self, master,
                       width=image.getWidth(),
                       height=image.getHeight())
    self.master.title(title)
    self.pack()
    master.resizable(0, 0)
    self.image = image
    self.height = image.getHeight()
    self.width = image.getWidth()
    self.autoflush = autoflush
    self.closed = False

   def close(self):

    self.closed = True
    self.master.destroy()
    self.image.canvas = None
    _root.quit()

   def isClosed(self):
    return self.closed

   def getHeight(self):

    return self.height

def getWidth(self):

    return self.width


 class Image:

 def __init__(self, *args):
    self.canvas = None
    if len(args) == 1:
        name = args[0]
        if type(name) != str:
            raise Exception('Must be a file name')
        if name[-4:].upper() != '.GIF':
            raise Exception('File must be a GIF')
        if not os.path.exists(args[0]):
            raise Exception('File not in current directory')
        self.image = tk.PhotoImage(file=args[0], master=_root)
        self.filename = args[0]
        self.width = self.image.width()
        self.height = self.image.height()
    else:  # arguments are width and height
        self.width, self.height = args
        self.image = tk.PhotoImage(master=_root,
                                   width=self.width,
                                   height=self.height)
        self.filename = ""

 def getWidth(self):

    return self.width

 def getHeight(self):

    return self.height

 def getPixel(self, x, y):

    value = self.image.get(x, y)
    if type(value) == int:
        return (value, value, value)
    elif type(value) == tuple:
        return value
    else:
        return tuple(map(int, value.split()))

 def setPixel(self, x, y, color):

    (r, g, b) = color
    r = round(r)
    g = round(g)
    b = round(b)
    color = (r, g, b)
    self.image.put("{#%02x%02x%02x}" % color, (x, y))

  def draw(self):

    if not self.canvas:
        self.canvas = ImageView(self,
                                self.filename)
    self.canvas.create_image(self.width // 2,
                             self.height // 2,
                             image=self.image)
    _root.mainloop()

 def save(self, filename=""):

    if filename == "":
        return
    else:
        self.filename = filename
    path, name = os.path.split(filename)
    ext = name.split(".")[-1]
    if ext != "gif":
        filename += ".gif"
        self.filename = filename
    self.image.write(self.filename, format="gif")

 def clone(self):
    new = Image(self.width, self.height)
    new.image = self.image.copy()
    return new

 def __str__(self):
    rep = ""
    if self.filename:
        rep += ("File name: " + self.filename + "\n")
    rep += ("Width:  " + str(self.width) + \
            "\nHeight: " + str(self.height))
    return rep


  _root = tk.Tk()
  _root.withdraw()

锐化.py 的代码:

  from image import Image

 def sharpen(image, degree, threshold):


  def getDiff(colorVal1, colorVal2):

    (r1, g1, b1) = colorVal1
    (r2, g2, b2) = colorVal2

    average1 = (r1 + g1 + b1) // 3
    average2 = (r2 + g2 + b2) // 3

    difference = average1 - average2

    return difference

   imageCopy = image.clone()  # Get a copy of the original image
   height = imageCopy.getHeight()  # Get image height
   width = imageCopy.getWidth()  # Get image width

   # Step through the pixels in the function to detect the edges
   for y in range(height - 1):
    for x in range(1, width):
        (r, g, b) = imageCopy.getPixel(x, y)  # Get the color of the current pixel
        (rBottom, gBottom, bBottom) = image.getPixel(x, y + 1)
        (rLeft, gLeft, bLeft) = image.getPixel(x - 1, y)
        if abs(getDiff((r, g, b), (rBottom, gBottom, bBottom))) > threshold or \
                abs(getDiff((r, g, b), (rLeft, gLeft, gBottom))) > threshold:
            newColor = [r, g, b]
            for index in range(len(newColor)):
                newColor[index] = max(newColor[index] - degree, 0)

            imageCopy.setPixel(x, y, tuple(newColor))

         """   
         else:
            newColor = [r, g, b]
            for item in range(len(newColor)):
                newColor[index] = newColor[index] + degree
                if newColor[index] > 255:
                    newColor[index] = 255
            imageCopy.setPixel(x, y, tuple(newColor))"""

  return imageCopy


def main():
filename = input("Enter the image file name: ")
image = Image(filename)
newimage = sharpen(image, 20, 15)
newimage.draw()


if __name__ == "__main__":
main()

这是smokey.gif,这是程序应该锐化并出现在新窗口中的图像: smokey

这是我运行程序时遇到的错误:

   Traceback (most recent call last):
   File "C:\Users\erikk\PycharmProjects\pythonProject\sharpen.py", line 65, in <module>
   main()
   File "C:\Users\erikk\PycharmProjects\pythonProject\sharpen.py", line 59, in main
   image = Image(filename)
   File "C:\Users\erikk\PycharmProjects\pythonProject\image.py", line 90, in __init__
   self.image = tk.PhotoImage(file=args[0], master=_root)
   File "C:\Users\erikk\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 4064, in __init__
   Image.__init__(self, 'photo', name, cnf, master, **kw)
   File "C:\Users\erikk\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line  4009, in __init__
   self.tk.call(('image', 'create', imgtype, name,) + options)
   _tkinter.TclError: couldn't recognize data in image file "Smokey.gif"

标签: pythonpython-3.xtkintertk

解决方案


推荐阅读