The following short code is meant to create an array with numpy, convert it into an image object with PIL and then insert into a canvas on a tkinter window.
from tkinter import *
from PIL import Image
root = Tk()
array = np.ones((40,40))*150
img = Image.fromarray(array)
canvas = Canvas(root,width=300,height=300)
canvas.pack()
canvas.create_image(20,20,anchor=NW,image=img)
root.mainloop()
This throws the error:
TclError: image "<PIL.Image.Image image mode=F size=40x40 at 0x7F42D3BC3290>" doesn't exist
You need to use PhotoImage from ImageTk.
Do this instead:
import tkinter as tk
import numpy as np
from PIL import Image, ImageTk
root = tk.Tk()
array = np.ones((40,40))*150
img = ImageTk.PhotoImage(image=Image.fromarray(array))
canvas = tk.Canvas(root,width=300,height=300)
canvas.pack()
canvas.create_image(20,20, anchor="nw", image=img)
root.mainloop()
tkinter supports only a few image formats directly, but one of them, PPM can be created easily from numpy data. So, here is a solution which converts an array directly to a tk.PhotoImage - no need to take the detour (and overhead!) of ImageTk:
import tkinter as tk
import numpy as np
def _photo_image(image: np.ndarray):
height, width = image.shape
data = f'P5 {width} {height} 255 '.encode() + image.astype(np.uint8).tobytes()
return tk.PhotoImage(width=width, height=height, data=data, format='PPM')
root = tk.Tk()
array = np.ones((40, 40)) * 150
img = _photo_image(array)
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
canvas.create_image(20, 20, anchor="nw", image=img)
root.mainloop()
The magic is in the function _photo_image which creates a portable pixmap header and appends the picture data, which must be an array of bytes.
Notes:
the above creates a portable graymap (PGM). With a slight modification, this also works with color images. These have one more dimension. So, use
height, width = image.shape[:2]
to extract the geometry and P6 for the magic value to pass in the header.
For example, to convert an openCV image (which is usually encoded as BGR), use:
import cv2
def _photo_image(image: np.ndarray):
height, width = image.shape[:2]
ppm_header = f'P6 {width} {height} 255 '.encode()
data = ppm_header + cv2.cvtColor(image, cv2.COLOR_BGR2RGB).tobytes()
return tk.PhotoImage(width=width, height=height, data=data, format='PPM')
the above link to the English Wikipedia page on netpbm does not fully explain the header format (you can find it in the examples, though). The German Wikipedia page on portable anymap has more details on the header: Magic Value, space, width, space, height, space, max-pixel-value, space
Related
from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()
I want to convert canvas content to a bitmap or other image, and then do other operations, such as rotating or scaling the image, or changing its coordinates.
Bitmaps can improve efficiency to show if I am no longer drawing.
What should I do?
You can either generate a postscript document (to feed into some other tool: ImageMagick, Ghostscript, etc):
from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()
cv.update()
cv.postscript(file="file_name.ps", colormode='color')
root.mainloop()
or draw the same image in parallel on PIL and on Tkinter's canvas (see: Saving a Tkinter Canvas Drawing (Python)). For example (inspired by the same article):
from Tkinter import *
import Image, ImageDraw
width = 400
height = 300
center = height//2
white = (255, 255, 255)
green = (0,128,0)
root = Tk()
# Tkinter create a canvas to draw on
cv = Canvas(root, width=width, height=height, bg='white')
cv.pack()
# PIL create an empty image and draw object to draw on
# memory only, not visible
image1 = Image.new("RGB", (width, height), white)
draw = ImageDraw.Draw(image1)
# do the Tkinter canvas drawings (visible)
cv.create_line([0, center, width, center], fill='green')
# do the PIL image/draw (in memory) drawings
draw.line([0, center, width, center], green)
# PIL image can be saved as .png .jpg .gif or .bmp file (among others)
filename = "my_drawing.jpg"
image1.save(filename)
root.mainloop()
I have found a great way of doing this which is really helpful. For it, you need the PIL module. Here is the code:
from PIL import ImageGrab
def getter(widget):
x=root.winfo_rootx()+widget.winfo_x()
y=root.winfo_rooty()+widget.winfo_y()
x1=x+widget.winfo_width()
y1=y+widget.winfo_height()
ImageGrab.grab().crop((x,y,x1,y1)).save("file path here")
What this does is you pass a widget name into the function. The command root.winfo_rootx() and the root.winfo_rooty() get the pixel position of the top left of the overall root window.
Then, the widget.winfo_x() and widget.winfo_y() are added to, basically just get the pixel coordinate of the top left hand pixel of the widget which you want to capture (at pixels (x,y) of your screen).
I then find the (x1,y1) which is the bottom left pixel of the widget. The ImageGrab.grab() makes a printscreen, and I then crop it to only get the bit containing the widget. Although not perfect, and won't make the best possible image, this is a great tool for just getting a image of any widget and saving it.
If you have any questions, post a comment! Hope this helped!
Use Pillow to convert from Postscript to PNG
from PIL import Image
def save_as_png(canvas,fileName):
# save postscipt image
canvas.postscript(file = fileName + '.eps')
# use PIL to convert to PNG
img = Image.open(fileName + '.eps')
img.save(fileName + '.png', 'png')
Maybe you can try to use widget_winfo_id to get the HWND of the canvas.
import win32gui
from PIL import ImageGrab
HWND = canvas.winfo_id() # get the handle of the canvas
rect = win32gui.GetWindowRect(HWND) # get the coordinate of the canvas
im = ImageGrab.grab(rect) # get image of the current location
A better way for #B.Jenkins's answer that doesn't need a reference to the root object:
from PIL import ImageGrab
def save_widget_as_image(widget, file_name):
ImageGrab.grab(bbox=(
widget.winfo_rootx(),
widget.winfo_rooty(),
widget.winfo_rootx() + widget.winfo_width(),
widget.winfo_rooty() + widget.winfo_height()
)).save(file_name)
On my system had serious issues with ghostscript and the ImageGrab in general. Solution draw on PIL Image, save as a file, load file on PhotoImage, which is used to create new TKinter Canvas.
canvas = Canvas(win, width=IMG_W, height=IMG_H)
img = PILImg.new("RGB", (IMG_W, IMG_H), "#000")
draw = ImageDraw.Draw(img)
draw.rectangle([x,y,w,h], fill=color, outline=border)
img.save("stock-chart.png")
copyImg = PhotoImage(file="stock-chart.png")
canvas.create_image(IMG_W_2, IMG_H_2, image=copyImg)
I can't display images longer (height) than about 30612 pixels high. I've read that there is a maximum height to canvas. I'd like to get the source file and extend that to 90 or 100k pixels in height. Conversely, I've seen suggested that a canvas may be buffered, if this is true, I have no clue how to implement it.. Any help is appreciated!
I am using code I found off Stack that is supposed to deal with large images, it does alright, but ultimately hit's the cavas height limit.
Canvas Limit
from tkinter import *
from PIL import ImageTk
from PIL import *
Image.MAX_IMAGE_PIXELS = None
class ScrolledCanvas(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.master.title("Spectrogram Viewer")
self.pack(expand=YES, fill=BOTH)
canv = Canvas(self, relief=SUNKEN)
canv.config(width=400, height=500)
# canv.config(scrollregion=(0,0,1000, 1000))
# canv.configure(scrollregion=canv.bbox('all'))
canv.config(highlightthickness=0)
sbarV = Scrollbar(self, orient=VERTICAL)
sbarH = Scrollbar(self, orient=HORIZONTAL)
sbarV.config(command=canv.yview)
sbarH.config(command=canv.xview)
canv.config(yscrollcommand=sbarV.set)
canv.config(xscrollcommand=sbarH.set)
sbarV.pack(side=RIGHT, fill=Y)
sbarH.pack(side=BOTTOM, fill=X)
canv.pack(side=LEFT, expand=YES, fill=BOTH)
self.im = Image.open("Test_3.tif")
width, height = self.im.size
canv.config(scrollregion=(0, 0, width, height))
self.im2 = ImageTk.PhotoImage(self.im)
self.imgtag = canv.create_image(0, 0, anchor="nw", image=self.im2)
ScrolledCanvas().mainloop()
I tried to put together a bigger image from displays of a grid of canvases. This looks like it might work, at least if you just want to display a big image. I have just tested with a small image and not paid any attention to memory or speed or anything...
from tkinter import *
from scrframe import VerticalScrolledFrame
root = Tk()
tiles = VerticalScrolledFrame(root) # Scrolled frame
tiles.grid()
tw = 90 # Tile width
th = 110 # Tile height
rows = 4 # Number of tiles/row
cols = 4 # Number of tiles/column
tile_list = [] # List of image tiles
img = PhotoImage(file='pilner.png')
for r in range(rows):
col_list = []
for c in range(cols):
tile = Canvas(tiles.interior, highlightthickness=0, bg='tan1',
width=tw, height=th)
tile.create_image(-c*tw, -r*th, image=img, anchor ='nw')
tile.grid(row=r, column=c)
col_list.append(tile)
tile_list.append(col_list)
root.mainloop()
Now, scrolling a frame seems to raise some problems, but there also seems to be solutions. I tried to use VerticalScrolledFrame as described in Python Tkinter scrollbar for frame and it works fine. As it only provides for a vertical scrollbar you'd have to implement horizontal scrollbar yourself. Maybe a few additional functions as scrolling with the mouse wheel, keyboard shortcuts or other would be useful.
I got the VerticalScrolledFrame from TKinter scrollable frame and modified it for Python 3.
This is the code I've come up with from several sources - Thanks to figbeam for all the help. Also, this is not pretty!!!! The button shows up in the center of the Tkinter window. If you'd like to modify this, please do.
from tkinter import *
from PIL import ImageTk as itk
from PIL import Image
import math
import numpy as np
Image.MAX_IMAGE_PIXELS = None #prevents the "photo bomb" warning from popping up. Have to have this for really large images.
#----------------------------------------------------------------------
# makes a simple window with a button right in the middle that let's you go "down" an image.
class MainWindow():
#----------------
def __init__(self, main):
# canvas for image
_, th, tw, rows, cols = self.getrowsandcols()
self.canvas = Canvas(main, width=tw, height=th)
self.canvas.grid(row=0, column=0)
# images
self.my_images = self.cropimages() # crop the really large image down into several smaller images and append to this list
self.my_image_number = 0 #
# set first image on canvas
self.image_on_canvas = self.canvas.create_image(0, 0, anchor = NW, image = self.my_images[self.my_image_number])
# button to change image
self.button = Button(main, text="DOWN", command=self.onDownButton)
self.button.grid(row=0, column=0)
#----------------
def getimage(self):
im = Image.open("Test_3.png") # import the image
im = im.convert("RGBA") # convert the image to color including the alpha channel (which is the transparency best I understand)
width, height = im.size # get the width and height
return width, height, im # return relevent variables/objects
def getrowsandcols(self):
width, height, im = self.getimage()
im = np.asarray(im) # Convert image to Numpy Array
tw = width # Tile width will equal the width of the image
th = int(math.ceil(height / 100)) # Tile height
rows = int(math.ceil(height / th)) # Number of tiles/row
cols = int(math.ceil(width / tw)) # Number of tiles/column
return im, th, tw, rows, cols #return selected variables
def cropimages(self):
self.my_images = [] # initialize list to hold Tkinter "PhotoImage objects"
im, th, tw, rows, cols = self.getrowsandcols() # pull in needed variables to crop the really long image
for r in range(rows): # loop row by row to crop all of the image
crop_im =im[r * th:((r * th) + th), 0:tw] # crop the image for the current row (r). (th) stands for tile height.
crop_im = Image.fromarray(crop_im) # convert the image from an Numpy Array to a PIL image.
crop_im = itk.PhotoImage(crop_im) # convert the PIL image to a Tkinter Photo Object (whatever that is)
self.my_images.append(crop_im) # Append the photo object to the list
crop_im = None
return self.my_images
def onDownButton(self):
# next image
self.my_image_number += 1 #every button pressed will
# return to first image
if self.my_image_number == len(self.my_images):
self.my_image_number = 0
# change image
self.canvas.itemconfig(self.image_on_canvas, image = self.my_images[self.my_image_number]) #attaches the image from the image list to the canvas
#----------------------------------------------------------------------
root = Tk()
MainWindow(root)
root.mainloop()
I'm trying to place a .png image within a LabelFrame in a Tkinter window. I imported PIL so .png image types should be supported (right?). I can't seem to get the image to show up.
Here is my revised code:
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
make_frame = LabelFrame(root, text="Sample Image", width=150, height=150)
make_frame.pack()
stim = "image.png"
width = 100
height = 100
stim1 = stim.resize((width, height), Image.ANTIALIAS)
img = ImageTk.PhotoImage(image.open(stim1))
in_frame = Label(make_frame, image = img)
in_frame.pack()
root.mainloop()
With this code, I got an AttributeError that reads: "'str' has no attribute 'resize'"
#Mickey,
You have to call the .resize method on the PIL.Image object and not the filename, which is a string. Also, you may prefer to use PIL.Image.thumbnail instead of PIL.Image.resize, for reasons described clearly here. Your code was close, but this might be what you need:
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
make_frame = LabelFrame(root, text="Sample Image", width=100, height=100)
make_frame.pack()
stim_filename = "image.png"
# create the PIL image object:
PIL_image = Image.open(stim_filename)
width = 100
height = 100
# You may prefer to use Image.thumbnail instead
# Set use_resize to False to use Image.thumbnail
use_resize = True
if use_resize:
# Image.resize returns a new PIL.Image of the specified size
PIL_image_small = PIL_image.resize((width,height), Image.ANTIALIAS)
else:
# Image.thumbnail converts the image to a thumbnail, in place
PIL_image_small = PIL_image
PIL_image_small.thumbnail((width,height), Image.ANTIALIAS)
# now create the ImageTk PhotoImage:
img = ImageTk.PhotoImage(PIL_image_small)
in_frame = Label(make_frame, image = img)
in_frame.pack()
root.mainloop()
I need to resize an image, but I want to avoid PIL, since I cannot make it work under OS X - don't ask me why...
Anyway since I am satisfied with gif/pgm/ppm, the PhotoImage class is ok for me:
photoImg = PhotoImage(file=imgfn)
images.append(photoImg)
text.image_create(INSERT, image=photoImg)
The problem is - how do I resize the image?
The following works only with PIL, which is the non-PIL equivalent?
img = Image.open(imgfn)
img = img.resize((w,h), Image.ANTIALIAS)
photoImg = ImageTk.PhotoImage(img)
images.append(photoImg)
text.image_create(INSERT, image=photoImg)
Thank you!
Because both zoom() and subsample() want integer as parameters, I used both.
I had to resize 320x320 image to 250x250, I ended up with
imgpath = '/path/to/img.png'
img = PhotoImage(file=imgpath)
img = img.zoom(25) #with 250, I ended up running out of memory
img = img.subsample(32) #mechanically, here it is adjusted to 32 instead of 320
panel = Label(root, image = img)
You have to either use the subsample() or the zoom() methods of the PhotoImage class. For the first option you first have to calculate the scale factors, simply explained in the following lines:
scale_w = new_width/old_width
scale_h = new_height/old_height
photoImg.zoom(scale_w, scale_h)
If you don't have PIL installed --> install it
(for Python3+ users --> use 'pip install pillow' in cmd)
from tkinter import *
import tkinter
import tkinter.messagebox
from PIL import Image
from PIL import ImageTk
master = Tk()
def callback():
print("click!")
width = 50
height = 50
img = Image.open("dir.png")
img = img.resize((width,height), Image.ANTIALIAS)
photoImg = ImageTk.PhotoImage(img)
b = Button(master,image=photoImg, command=callback, width=50)
b.pack()
mainloop()
I just had the same problem, and I found that #Memes' answer works rather well. Just make sure to reduce your ratio as much as possible, as subsample() takes a rather long time to run for some reason.
Basically, the image is zoomed out to the least common factor of the two sizes, and then being subsidized by the origonal size. This leaves you with the image of the desired size.
I had a requirement where I wanted to open an image, resize it, keeping the aspect ratio, save it under a new name, & display it in a tkinter window (using Linux Mint). After looking through dozens of forum questions, and dealing with some weird errors (semmingly involving the PIL to Pillow fork in Python 3.x), I was able to develop some code that works, using a predefined new maximum width or new maximum height (scaling up or down as necessary), and a Canvas object, where the image is displayed centered in the frame. Note that I did not include the file dialogs, just a hardcoded Image open & save for one file:
from tkinter import *
from PIL import ImageTk, Image
import shutil,os
from tkinter import filedialog as fd
maxwidth = 600
maxheight = 600
mainwindow = Tk()
picframe = Frame(mainwindow)
picframe.pack()
canvas = Canvas(picframe, width = maxwidth, height = maxheight)
canvas.pack()
img = Image.open("/home/user1/Pictures/abc.jpg")
width, height = img.size # Code to scale up or down as necessary to a given max height or width but keeping aspect ratio
if width > height:
scalingfactor = maxwidth/width
width = maxwidth
height = int(height*scalingfactor)
else:
scalingfactor = maxheight/height
height = maxheight
width = int(width*scalingfactor)
img = img.resize((width,height), Image.ANTIALIAS)
img.save("/home/user1/Pictures/Newabc.jpg")
img = ImageTk.PhotoImage(img) # Has to be after the resize
canvas.create_image(int(maxwidth/2)-int(width/2), int(maxheight/2)-int(height/2), anchor=NW, image=img) # No autocentering in frame, have to manually calculate with a new x, y coordinate based on a NW anchor (upper left)
I'm currently using PIL to display images in Tkinter. I'd like to temporarily resize these images so that they can be viewed more easily. How can I go about this?
Snippet:
self.pw.pic = ImageTk.PhotoImage(Image.open(self.pic_file))
self.pw.pic_label = TK.Label(self.pw , image=self.pw.pic,borderwidth=0)
self.pw.pic_label.grid(column=0,row=0)
Here's what I do and it works pretty well...
image = Image.open(Image_Location)
image = image.resize((250, 250), Image.ANTIALIAS) ## The (250, 250) is (height, width)
self.pw.pic = ImageTk.PhotoImage(image)
There you go :)
EDIT:
Here is my import statement:
from Tkinter import *
import tkFont
from PIL import Image
And here is the complete working code I adapted this example from:
im_temp = Image.open(Image_Location)
im_temp = im_temp.resize((250, 250), Image.ANTIALIAS)
im_temp.save("ArtWrk.ppm", "ppm") ## The only reason I included this was to convert
## The image into a format that Tkinter woulden't complain about
self.photo = PhotoImage(file="ArtWrk.ppm") ## Open the image as a tkinter.PhotoImage class()
self.Artwork.destroy() ## Erase the last drawn picture (in the program the picture I used was changing)
self.Artwork = Label(self.frame, image=self.photo) ## Sets the image too the label
self.Artwork.photo = self.photo ## Make the image actually display (If I don't include this it won't display an image)
self.Artwork.pack() ## Repack the image
And here are the PhotoImage class docs: http://www.pythonware.com/library/tkinter/introduction/photoimage.htm
Note...
After checking the pythonware documentation on ImageTK's PhotoImage class (Which is very sparse) I appears that if your snippet works than this should as well as long as you import the PIL "Image" Library an the PIL "ImageTK" Library and that both PIL and tkinter are up-to-date. On another side-note I can't even find the "ImageTK" module life for the life of me. Could you post your imports?
if you don't want save it you can try it:
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
same = True
#n can't be zero, recommend 0.25-4
n=2
path = "../img/Stalin.jpeg"
image = Image.open(path)
[imageSizeWidth, imageSizeHeight] = image.size
newImageSizeWidth = int(imageSizeWidth*n)
if same:
newImageSizeHeight = int(imageSizeHeight*n)
else:
newImageSizeHeight = int(imageSizeHeight/n)
image = image.resize((newImageSizeWidth, newImageSizeHeight), Image.ANTIALIAS)
img = ImageTk.PhotoImage(image)
Canvas1 = Canvas(root)
Canvas1.create_image(newImageSizeWidth/2,newImageSizeHeight/2,image = img)
Canvas1.config(bg="blue",width = newImageSizeWidth, height = newImageSizeHeight)
Canvas1.pack(side=LEFT,expand=True,fill=BOTH)
root.mainloop()
the easiest might be to create a new image based on the original, then swap out the original with the larger copy. For that, a tk image has a copy method which lets you zoom or subsample the original image when making the copy. Unfortunately it only lets you zoom/subsample in factors of 2.