1
+ # Import the necessary packages
2
+ from tkinter import *
3
+ from PIL import Image
4
+ from PIL import ImageTk
5
+ import tkinter .filedialog
6
+ import cv2
7
+
8
+ def select_image ():
9
+ # Grab a reference to the image panels
10
+ global panelA , panelB
11
+ # Open a file chooser dialog and allow the user to select an input image
12
+ path = tkinter .filedialog .askopenfilename ()
13
+
14
+ # Ensure a file path was selected
15
+ if len (path ) > 0 :
16
+ # Load the image from disk, convert it to grayscale, and detect edges in it
17
+ image = cv2 .imread (path )
18
+ gray = cv2 .cvtColor (image , cv2 .COLOR_BGR2GRAY )
19
+ edged = cv2 .Canny (gray , 50 , 100 )
20
+ # OpenCV represents images in BGR order; however PIL represents images in RGB order, so we need to swap the channels
21
+ image = cv2 .cvtColor (image , cv2 .COLOR_BGR2RGB )
22
+ # Convert the images to PIL format
23
+ image = Image .fromarray (image )
24
+ edged = Image .fromarray (edged )
25
+ # and then to ImageTk format
26
+ image = ImageTk .PhotoImage (image )
27
+ edged = ImageTk .PhotoImage (edged )
28
+
29
+ # If the panels are None, initialize them
30
+ if panelA is None or panelB is None :
31
+ # The first panel will store our original image
32
+ panelA = Label (image = image )
33
+ panelA .image = image
34
+ panelA .pack (side = "left" , padx = 10 , pady = 10 )
35
+ # While the second panel will store the edge map
36
+ panelB = Label (image = edged )
37
+ panelB .image = edged
38
+ panelB .pack (side = "right" , padx = 10 , pady = 10 )
39
+ # Otherwise, update the image panels
40
+ else :
41
+ # Update the panels
42
+ panelA .configure (image = image )
43
+ panelB .configure (image = edged )
44
+ panelA .image = image
45
+ panelB .image = edged
46
+
47
+ # Initialize the window toolkit along with the two image panels
48
+ root = Tk ()
49
+ panelA = None
50
+ panelB = None
51
+ # Create a button, then when pressed, will trigger a file chooser dialog and allow the user to select an input image; then add the button to the GUI
52
+ btn = Button (root , text = "Select an image" , command = select_image )
53
+ btn .pack (side = "bottom" , fill = "both" , expand = "yes" , padx = "10" , pady = "10" )
54
+ # Kick off the GUI
55
+ root .mainloop ()
0 commit comments