Warning: Can not open [/home/conf/public_html/cgi-bin/show_python.log]. Ignore
No title
Download script from image_view.py
Related files:
import sys
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import cv2
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
infile = None
width = 800
height = 800
nargv = len(sys.argv)
if nargv >= 2: infile = sys.argv[1]
if nargv >= 3: width = int(sys.argv[2])
if nargv >= 4: height = int(sys.argv[3])
class ImageViewer:
def __init__(self, root, file_path = None, width = 800, height = 800):
self.root = root
self.file_path = infile
self.root.title("Image Viewer")
self.root_frame = tk.Frame(root)
frame = self.root_frame
frame.pack(expand = True, fill = tk.BOTH)
self.btn_open = tk.Button(frame, text = "Open Image", command = self.open_image)
self.btn_open.pack()
var_width = tk.IntVar(value = width)
var_height = tk.IntVar(value = height)
entry_frame = tk.Frame(frame)
entry_frame.pack(expand = True, fill = tk.BOTH)
self.label_width = tk.Label(entry_frame, text = "Width:")
self.label_width.pack(side = tk.LEFT)
self.entry_width = tk.Entry(entry_frame, textvariable = var_width)
self.entry_width.pack(side = tk.LEFT)
self.label_height = tk.Label(entry_frame, text="Height:")
self.label_height.pack(side = tk.LEFT)
self.entry_height = tk.Entry(entry_frame, textvariable = var_height)
self.entry_height.pack(side = tk.LEFT)
if file_path:
img = self.read_image(file_path)
self.display_image(img)
def open_image(self):
file_path = filedialog.askopenfilename()
if file_path:
img = self.read_image(file_path)
self.display_image(img)
def read_image(self, file_path):
# return self.read_image_cv2(file_path)
return self.read_image_pil(file_path)
def display_image(self, file_path):
# self.display_image_canvas(file_path)
self.display_image_mpl(file_path)
def read_image_cv2(self, file_path):
img = cv2.imread(file_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
return img
def read_image_pil(self, file_path):
img = Image.open(file_path)
return img
def display_image_canvas(self, img):
width = int(self.entry_width.get())
height = int(self.entry_height.get())
img_resized = img.resize((width, height))
self.img_tk = ImageTk.PhotoImage(img_resized)
self.canvas = tk.Canvas(self.root_frame)
self.canvas.pack()
self.canvas.config(width = width, height = height)
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.img_tk)
def display_image_mpl(self, img):
width = int(self.entry_width.get())
height = int(self.entry_height.get())
img_resized = img.resize((width, height))
fig = Figure(figsize = (width / 100, height / 100))
ax = fig.add_subplot(111)
ax.imshow(img_resized)
ax.axis('off')
self.canvas = FigureCanvasTkAgg(fig, master = self.root)
self.canvas.draw()
self.canvas.get_tk_widget().pack()
if __name__ == "__main__":
root = tk.Tk()
app = ImageViewer(root, infile, width, height)
root.mainloop()