Pillow/Scripts/thresholder.py

81 lines
1.9 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2010-07-31 06:52:47 +04:00
#
# The Python Imaging Library
# $Id$
#
# this demo script illustrates how a 1-bit BitmapImage can be used
# as a dynamically updated overlay
#
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
2012-10-17 06:58:29 +04:00
2010-07-31 06:52:47 +04:00
from PIL import Image, ImageTk
#
# an image viewer
2015-04-24 02:41:33 +03:00
class UI(tkinter.Frame):
2015-04-24 02:41:33 +03:00
def __init__(self, master, im, value=128):
tkinter.Frame.__init__(self, master)
2010-07-31 06:52:47 +04:00
self.image = im
self.value = value
self.canvas = tkinter.Canvas(self, width=im.size[0], height=im.size[1])
2010-07-31 06:52:47 +04:00
self.backdrop = ImageTk.PhotoImage(im)
self.canvas.create_image(0, 0, image=self.backdrop, anchor=tkinter.NW)
2010-07-31 06:52:47 +04:00
self.canvas.pack()
scale = tkinter.Scale(self, orient=tkinter.HORIZONTAL, from_=0, to=255,
resolution=1, command=self.update_scale,
length=256)
2010-07-31 06:52:47 +04:00
scale.set(value)
scale.bind("<ButtonRelease-1>", self.redraw)
scale.pack()
# uncomment the following line for instant feedback (might
# be too slow on some platforms)
# self.redraw()
2015-04-02 11:46:35 +03:00
def update_scale(self, value):
2016-05-10 16:07:16 +03:00
self.value = float(value)
2010-07-31 06:52:47 +04:00
self.redraw()
2015-04-24 02:41:33 +03:00
def redraw(self, event=None):
2010-07-31 06:52:47 +04:00
# create overlay (note the explicit conversion to mode "1")
2015-04-24 02:41:33 +03:00
im = self.image.point(lambda v, t=self.value: v >= t, "1")
2010-07-31 06:52:47 +04:00
self.overlay = ImageTk.BitmapImage(im, foreground="green")
# update canvas
self.canvas.delete("overlay")
self.canvas.create_image(0, 0, image=self.overlay, anchor=tkinter.NW,
2015-04-24 02:41:33 +03:00
tags="overlay")
2010-07-31 06:52:47 +04:00
# --------------------------------------------------------------------
# main
if len(sys.argv) != 2:
print("Usage: thresholder file")
sys.exit(1)
root = tkinter.Tk()
2010-07-31 06:52:47 +04:00
im = Image.open(sys.argv[1])
if im.mode != "L":
im = im.convert("L")
# im.thumbnail((320,200))
UI(root, im).pack()
root.mainloop()