Pillow/Scripts/thresholder.py

75 lines
1.8 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
#
2012-10-17 06:58:29 +04:00
try:
from tkinter import *
except ImportError:
from Tkinter import *
2010-07-31 06:52:47 +04:00
from PIL import Image, ImageTk
import sys
#
# an image viewer
2015-04-24 02:41:33 +03:00
2010-07-31 06:52:47 +04:00
class UI(Frame):
2015-04-24 02:41:33 +03:00
def __init__(self, master, im, value=128):
2010-07-31 06:52:47 +04:00
Frame.__init__(self, master)
self.image = im
self.value = value
self.canvas = Canvas(self, width=im.size[0], height=im.size[1])
self.backdrop = ImageTk.PhotoImage(im)
self.canvas.create_image(0, 0, image=self.backdrop, anchor=NW)
self.canvas.pack()
scale = Scale(self, orient=HORIZONTAL, from_=0, to=255,
2015-04-02 11:46:35 +03:00
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):
2010-07-31 06:52:47 +04:00
self.value = eval(value)
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=NW,
2015-04-24 02:41:33 +03:00
tags="overlay")
2010-07-31 06:52:47 +04:00
# --------------------------------------------------------------------
# main
root = Tk()
im = Image.open(sys.argv[1])
if im.mode != "L":
im = im.convert("L")
# im.thumbnail((320,200))
UI(root, im).pack()
root.mainloop()