I am loading python dictionary with multiple polygons. Polygon points are obtained from mouse click on different position of image. The script displays image to user for selection of different points of polygons. The user will click on different position by mouse right click. When the user clicks left mouse button, a polygon is created and added to dictionary Dict_Polygons with a label. The list list_of_points is cleared as new points for new polygon will be added to this list. The issue is that Dict_Polygon is not loaded with items. Here is the complete code.
import math
import pickle
from Tkinter import *
import Image, ImageTk, ImageDraw
import numpy as np
coord=[] # for saving coord of each click position
Dict_Polygon={} # Dictionary for saving polygon
list_of_points=[]
flag=True
label=0
def draw_lines(event):
mouse_xy = (event.x, event.y)
func_Draw_lines(mouse_xy)
def func_Draw_lines(mouse_xy):
func_Draw_Dot(mouse_xy)
center_x, center_y = mouse_xy
if canvas.old_coords:
x1, y1 = canvas.old_coords
canvas.create_line(center_x, center_y, x1, y1)
# add clicked positions to list
if flag==True:
list_of_points.append(mouse_xy)
canvas.old_coords = center_x, center_y
def func_Draw_Dot(coord):
x_coord, y_coord=coord
#draw dot over position which is clicked
x1, y1 = (x_coord - 1), (y_coord - 1)
x2, y2 = (x_coord + 1), (y_coord + 1)
canvas.create_oval(x1, y1, x2, y2, fill='green', outline='green', width=5)
# This function will be called when the user wants to specify class, so a polygon will be drawn.
def func_draw_polygon(event):
numberofPoint=len(list_of_points)
if numberofPoint>2:
print ("test")
canvas.create_polygon(list_of_points, fill='', outline='green', width=2)
Dict_Polygon[label]=list_of_points
list_of_points[:]=[]
# del list_of_points[:] # clear list elements to add new polygon points
canvas.old_coords=None
global label
label=label+1
print (Dict_Polygon.items())
else:
print('Select minemum 3 points')
# Main function
if __name__ == '__main__':
root = Tk()
# Input image
img = Image.open("e.png")
# Draw canvas for iput image to pop up image for clicks
filename = ImageTk.PhotoImage(img)
canvas = Canvas(root,height=img.size[0],width=img.size[0])
canvas.image = filename
canvas.create_image(0,0,anchor='nw',image=filename)
canvas.pack()
canvas.old_coords = None
# bind function to canvas to generate event
canvas.bind("<Button 3>", draw_lines)
canvas.bind("<Button 1>", func_draw_polygon)
root.mainloop()