Сшить изображения в Python с помощью Tkinter - PullRequest
1 голос
/ 09 июля 2020

Я делаю сшиватель изображений с помощью Tkinter (в Python 3.7.3), используя свой Raspberry Pi 4, и получаю следующую ошибку:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/PIL/Image.py", line 1974, in save
    format = EXTENSION[ext]
KeyError: ''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "/home/pi/Documents/python/image_station/new.py", line 98, in <lambda>
    stitch_btn = Button(frame, text="Submit", command=lambda: stitch(image1, image2))
  File "/home/pi/Documents/python/image_station/new.py", line 72, in stitch
    new_im.save(new_dir+"/")
  File "/usr/lib/python3/dist-packages/PIL/Image.py", line 1976, in save
    raise ValueError('unknown file extension: {}'.format(ext))
ValueError: unknown file extension: 

Я новичок ie в Python особенно в Tkinter. Насколько я знаю, мне нужно использовать лямбда: для вызова функции, которая мне нужна для ввода данных. Но потом я не мог понять, почему я получаю ошибку из-за неизвестного расширения файла ..

Вот мой код:

import os, sys
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image

root  = Tk() #window widget
root.title("Image Stitching Station")
root.geometry("600x250")


def open1():
    global image1
    global image1_re
    global image1_label
    root.filename1 = filedialog.askopenfilename(initialdir="/home/pi/Documents/python/image_station/images/", title="Select a File", filetypes=(("jpg files", "*.jpg"),("png files", "*.png"),("all files", "*.*")))
    image1 = Image.open(root.filename1)
    print('Image1 is: ' + root.filename1)
    image1_resized = image1.resize((150, 150), Image.ANTIALIAS) #resize only for display purposes
    image1_re = ImageTk.PhotoImage(image1_resized)
    
    image1_label=Label(root, image=image1_re)
    image1_label.grid(row=0, column=1)

def open2():
    global image2
    global image2_re
    global image2_label
    root.filename2 = filedialog.askopenfilename(initialdir="/home/pi/Documents/python/image_station/images/", title="Select a File", filetypes=(("jpg files", "*.jpg"),("png files", "*.png"),("all files", "*.*")))
    image2 = Image.open(root.filename2)
    print('Image2 is: ' + root.filename2)
    image2_resized = image2.resize((150, 150), Image.ANTIALIAS) #resize only for display purposes
    image2_re = ImageTk.PhotoImage(image2_resized) 
    
    image2_label=Label(root, image=image2_re)
    image2_label.grid(row=0, column=2)

def clear():
    global image1
    global image2
    global image1_re
    global image2_re
    global image1_label
    global image2_label
    image1_label.destroy()
    image2_label.destroy()
    
def save():
    global new_dir
    root.directory = filedialog.askdirectory(initialdir="/home/pi/Desktop/", title="Select a Folder")
    new_dir = root.directory
    print(new_dir)

def stitch(name1, name2):
    global image1
    global image2
    global image1_re
    global image2_re
    global new_dir
    images = ([image1, image2])
    widths, heights = zip(*(i.size for i in images))

    total_width = sum(widths)
    max_height = max(heights)

    new_im = Image.new('RGB', (total_width, max_height))

    x_offset = 0
    for im in images:
      new_im.paste(im, (x_offset,0))
      x_offset += im.size[0]

    new_im.save(new_dir+"/")    

###################################
###MANUAL IMAGE STITCHING STATION###
###################################
global image1
global image2
global image1_re
global image2_re
global new_dir
frame = LabelFrame(root, text="Manul Image Stitching Station", height = 400, width=600, padx=5, pady=5)
frame.grid(row=0, column=0, padx=10,pady=10)




########   LABELS   ########
folder_label = Label(frame, text="Select folder to save your image.")
my_btn1_label = Label(frame, text="Select front image")
my_btn2_label = Label(frame, text="Select back image")


########   BUTTONS  ########
my_btn1 = Button(frame, text="Open Image 1", command=open1)
my_btn2 = Button(frame, text="Open Image 2", command=open2)
folder_button = Button(frame, text="Choose a Folder", command=save)
stitch_btn = Button(frame, text="Submit", command=lambda: stitch(image1, image2))
clear_btn = Button(frame, text="Clear", command=clear)

#GRIDS
my_btn1_label.grid(row=0, column=0)
my_btn1.grid(row=1, column=0)
my_btn2_label.grid(row=2, column=0)
my_btn2.grid(row=3, column=0)
folder_button.grid(row=4, column=0)
stitch_btn.grid(row=5, column=0)
clear_btn.grid(row=5, column=1)






button_quit = Button(root, text="Exit Program", command=root.destroy) #also root.quit
button_quit.grid(row=10,column=0)
root.mainloop()

1 Ответ

0 голосов
/ 09 июля 2020

Ваш сценарий хочет сохранить файл в каталог, но имя / расширение файла не указаны. Вы должны передать путь к файлу в new_im.save() (не только путь к каталогу).

Правильная строка:

new_im.save("{}".format(os.path.join(new_dir, "new_img.jpg")))
...