将GUI集成到我的裁剪和堆栈程序中



我是python(3.8(的新手,我刚刚写了一个程序,可以在目录中获取图像并裁剪它们,然后将它们全部堆叠。我目前正在尝试添加一个GUI,使其看起来更好。我已经阅读了一些关于如何使用tkinter的指南,他们都单独讨论了每个小部件。我对使用GUI中的Entry信息放入程序中运行的表示法有点困惑。我已经为该程序编写了一个通用GUI。在我的程序中,输入文件的文件目录和保存位置不变,用户可以输入(x1,y1(、(x2,y2(和图像数量。如果我想让我的GUI提示输入和保存文件目录,我一直在尝试这样做:

def inputfile():
master.filename = filedialog.askdirectory()
print(master.filename)
...
input = Button(master, text="Input Files", command="inputfile")
input.grid(column=5, row=6, columnspan=2, pady=6)

然后在我的代码中,用filename.get((替换目录

for filename in natsorted(
glob.glob("..\One_Dimensional_Reaction_Diffusion_Program\image_crop_input\" + "*.*", 
recursive=True)):
img = Image.open(filename)

我还试着用x1input.get((将所有的x1、y1、x2、y2替换为代码值。这是正确的方法吗?

附件是程序和GUI代码。谢谢你抽出时间。

程序

from PIL import Image
from natsort import natsorted
import glob
import gc
# Convert coordinate list into variables
print("Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points")
coordinates = list(map(int, input("Separate values with a space (x1 y1 x2 y2): ").strip().split()))[:4]
x1, y1, x2, y2 = coordinates
image_count = int(input("How many images are being stacked? "))
print("Generating image...")
# Generate final image first
# Width dependent on whether image is horizontal or vertical
if (y2 - y1) > (x2 - x1):
width = (y2 - y1)
height = (x2 - x1)
else:
width = (x2 - x1)
height = (y2 - y1)
# Width is constant, total_height accounts for height above and the total number of images
total_height = (image_count * height)
new_im = Image.new('RGB', (width, total_height))  # Create a new colored image (RGB)
# Keep outside of loop, if not, will reset y_offset each time
# Indicates position of where to paste cropped image
# Counter used to show progress of program
y_offset = 0
counter = 0
# Accessing all the files using the glob module
# The function natsorted sorts values the way Windows does
# ..\ allows the program to obtained images from the data file relative to the script's location
# Opens all the files with the variable img in folder and adds them one by one to a list named image_list
for filename in natsorted(
glob.glob("..\One_Dimensional_Reaction_Diffusion_Program\image_crop_input\" + "*.*", recursive=True)):
img = Image.open(filename)
# Cropping function
selected_region = (x1, y1, x2, y2)  # selected region from previous user input
cropped_region = img.crop(selected_region)  # taking opened image and cropping to selected region
if (y2 - y1) > (x2 - x1):  # If cropped area is vertical, rotate into horizontal position
rotated_image = cropped_region.rotate(90, expand=1)  # Expand 1 ensures image isn't cut off while rotating
else:
rotated_image = cropped_region  # Does nothing if image is horizontal
img.close()  # Closes the initially opened image
gc.collect()
new_im.paste(rotated_image, (0, y_offset))  # (x,y) indicates which direction to offset in
y_offset += rotated_image.size[1]  # y_offset (which had position 0) + the height of the image
counter += 1
print(counter, " out of ", image_count, "completed.")  # Shows progress of program
if counter == image_count:  # Will stop program when counter reaches number of images
break
final_im = new_im.rotate(180, expand=1)  # stacking goes from top to bottom, rotate images at the end
final_im.save("..\One_Dimensional_Reaction_Diffusion_Program\image_crop_output\stacked_image.tiff", quality=95)
print("Image completed and can be found in the output folder.")
input("Press ENTER to close program.")  # prevents prompt from instantly closing

GUI代码

from tkinter import *
from tkinter import filedialog
from PIL import Image
from natsort import natsorted
import glob
import gc
master = Tk()
master.title("One Dimensional Reaction Diffusion Program")
master.geometry("440x270")
def inputfile():
master.filename = filedialog.askdirectory()
print(master.filename)

header1 = Label(master, text="One Dimensional Reaction Diffusion Programn"
"Created by: Alexander Tangn")
header1.grid(sticky="N", columnspan=8)
instructions = Label(master, text="Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points:")
instructions.grid(sticky="W", columnspan=8)
x1 = Label(master, text="x1: ")
x1.grid(sticky="E", column=0, row=2)
x1input = Entry(master, width=5)
x1input.grid(sticky="W", column=1, row=2)
y1 = Label(master, text="y1: ")
y1.grid(sticky="E", column=2, row=2)
y1input = Entry(master, width=5)
y1input.grid(sticky="W", column=3, row=2)
x2 = Label(master, text="x2: ")
x2.grid(sticky="E", column=4, row=2)
x2input = Entry(master, width=5)
x2input.grid(sticky="W", column=5, row=2)
y2 = Label(master, text="y2: ")
y2.grid(sticky="E", column=6, row=2)
y2input = Entry(master, width=5)
y2input.grid(sticky="W", column=7, row=2, pady=12)
count = Label(master, text="How many images are being stacked? ")
count.grid(sticky="W", column=0, row=4, columnspan=4)
countinput = Entry(master, width=5)
countinput.grid(stick="W", column=5, row=4, pady=3)
step1 = Label(master, text="1. Select the file location: ")
step1.grid(sticky="W", column=0, row=6, columnspan=4)
step2 = Label(master, text="2. Select the save location: ")
step2.grid(sticky="W", column=0, row=7, columnspan=4)
input = Button(master, text="Input Files", command="inputfile")
input.grid(column=5, row=6, columnspan=2, pady=6)
output = Button(master, text="Output Location")
output.grid(column=5, row=7, columnspan=2)
run = Button(master, text="Run", font="Helvetica, 18", bg="blue", fg="white")
run.grid(sticky="S", column=5, row=8, columnspan=2, pady=6)

mainloop()

用于处理图像的第一个代码必须放入函数中(但没有input()(,以便使用参数运行它

def process(directory, coordinates, image_count, outputdirectory=None):

然后您可以使用input()或GUI或网页来获取参数并运行此函数

在同一个文件中,我使用

if __name__ == "__main__":
main()

以运行此脚本并使用input()获取参数并运行process()

它也可以导入到其他脚本并运行process(),而无需启动main()

图像处理.py

from PIL import Image
from natsort import natsorted
import glob
import gc
import os   # os.path.join(directory, filename)
def process(directory, coordinates, image_count, outputdirectory=None):
x1, y1, x2, y2 = coordinates
# Generate final image first
# Width dependent on whether image is horizontal or vertical
if (y2 - y1) > (x2 - x1):
width = (y2 - y1)
height = (x2 - x1)
else:
width = (x2 - x1)
height = (y2 - y1)
# Width is constant, total_height accounts for height above and the total number of images
total_height = (image_count * height)
new_im = Image.new('RGB', (width, total_height))  # Create a new colored image (RGB)
# Keep outside of loop, if not, will reset y_offset each time
# Indicates position of where to paste cropped image
# Counter used to show progress of program
y_offset = 0
counter = 0
# Accessing all the files using the glob module
# The function natsorted sorts values the way Windows does
# ..\ allows the program to obtained images from the data file relative to the script's location
# Opens all the files with the variable img in folder and adds them one by one to a list named image_list
for filename in natsorted(glob.glob( os.path.join(directory, "*.*"), recursive=True)):
img = Image.open(filename)
# Cropping function
selected_region = (x1, y1, x2, y2)  # selected region from previous user input
cropped_region = img.crop(selected_region)  # taking opened image and cropping to selected region
if (y2 - y1) > (x2 - x1):  # If cropped area is vertical, rotate into horizontal position
rotated_image = cropped_region.rotate(90, expand=1)  # Expand 1 ensures image isn't cut off while rotating
else:
rotated_image = cropped_region  # Does nothing if image is horizontal
img.close()  # Closes the initially opened image
gc.collect()
new_im.paste(rotated_image, (0, y_offset))  # (x,y) indicates which direction to offset in
y_offset += rotated_image.size[1]  # y_offset (which had position 0) + the height of the image
counter += 1
print(counter, " out of ", image_count, "completed.")  # Shows progress of program
if counter == image_count:  # Will stop program when counter reaches number of images
break
final_im = new_im.rotate(180, expand=1)  # stacking goes from top to bottom, rotate images at the end
if outputdirectory is None:
outputdirectory = directory
final_im.save( os.path.join(outputdirectory, "stacked_image.tiff"), quality=95)
def main():
# Convert coordinate list into variables
print("Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points")
coordinates = list(map(int, input("Separate values with a space (x1 y1 x2 y2): ").strip().split()))[:4]
image_count = int(input("How many images are being stacked? "))
print("Generating image...")
process(directory, coordinates, image_count)
print("Image completed and can be found in the output folder.")
input("Press ENTER to close program.")  # prevents prompt from instantly closing
if __name__ == "__main__":
main()

现在您可以将它导入GUI,并使用按钮运行从GUI获取参数的函数,然后运行process()

BTW:必须是函数名command=function_name,而不是字符串"function_name"

gui.py

from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image
from natsort import natsorted
import glob
import gc
import imageprocess
# --- functions ---
def inputfile():
master.inputdirectory = filedialog.askdirectory()
print(master.inputdirectory)
def outputfile():
master.outputdirectory = filedialog.askdirectory()
print(master.outputdirectory)
def run():
try:
coordinates = [int(x1input.get()), int(x2input.get()), int(y1input.get()), int(y2input.get())]
image_count = int(countinput.get())
imageprocess.process(master.inputdirectory, coordinates, image_count, master.outputdirectory)
except Exception as ex:
print('ex:', ex)
messagebox.showwarning("Warning", "Wrong arguments:n" + str(ex))
# --- main ---
master = Tk()
master.inputdirectory = None   # default value at start
master.outputdirectory = None  # default value at start
master.title("One Dimensional Reaction Diffusion Program")
master.geometry("440x270")
header1 = Label(master, text="One Dimensional Reaction Diffusion Programn"
"Created by: Alexander Tangn")
header1.grid(sticky="N", columnspan=8)
instructions = Label(master, text="Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points:")
instructions.grid(sticky="W", columnspan=8)
x1 = Label(master, text="x1: ")
x1.grid(sticky="E", column=0, row=2)
x1input = Entry(master, width=5)
x1input.grid(sticky="W", column=1, row=2)
y1 = Label(master, text="y1: ")
y1.grid(sticky="E", column=2, row=2)
y1input = Entry(master, width=5)
y1input.grid(sticky="W", column=3, row=2)
x2 = Label(master, text="x2: ")
x2.grid(sticky="E", column=4, row=2)
x2input = Entry(master, width=5)
x2input.grid(sticky="W", column=5, row=2)
y2 = Label(master, text="y2: ")
y2.grid(sticky="E", column=6, row=2)
y2input = Entry(master, width=5)
y2input.grid(sticky="W", column=7, row=2, pady=12)
count = Label(master, text="How many images are being stacked? ")
count.grid(sticky="W", column=0, row=4, columnspan=4)
countinput = Entry(master, width=5)
countinput.grid(stick="W", column=5, row=4, pady=3)
step1 = Label(master, text="1. Select the file location: ")
step1.grid(sticky="W", column=0, row=6, columnspan=4)
step2 = Label(master, text="2. Select the save location: ")
step2.grid(sticky="W", column=0, row=7, columnspan=4)
btn_input = Button(master, text="Input Files", command=inputfile)
btn_input.grid(column=5, row=6, columnspan=2, pady=6)
btn_output = Button(master, text="Output Location", command=outputfile)
btn_output.grid(column=5, row=7, columnspan=2)
btn_run = Button(master, text="Run", font="Helvetica, 18", bg="blue", fg="white", command=run)
btn_run.grid(sticky="S", column=5, row=8, columnspan=2, pady=6)
mainloop()

它需要检查小部件中的值,并在参数错误时显示带有警告的窗口。但代码开始工作

最新更新