您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

62 行
2.4KB

  1. import tkinter as tk
  2. import numpy as np
  3. from PIL import ImageGrab, ImageTk
  4. from PIL.Image import Resampling
  5. class DigitDrawer(tk.Frame):
  6. def __init__(self, parent, canvas_width, canvas_height):
  7. super().__init__(parent)
  8. self.canvas_width = canvas_width
  9. self.canvas_height = canvas_height
  10. self.brush_size = 3
  11. self.update_ui()
  12. def clear_ui(self):
  13. for widget in self.winfo_children():
  14. widget.destroy()
  15. def update_ui(self):
  16. self.clear_ui()
  17. # Create a Canvas to draw on
  18. self.canvas = tk.Canvas(self, width=self.canvas_width, height=self.canvas_height, bg='white')
  19. self.canvas.pack(padx=10, pady=10)
  20. self.canvas_demo = tk.Canvas(self, width=28, height=28, bg='white')
  21. self.canvas_demo.pack(padx=10, pady=10)
  22. # Clear Button
  23. self.clear_button = tk.Button(self, text="Clear", command=self.clear_canvas)
  24. self.clear_button.pack(expand=True, fill='both')
  25. # Bind mouse events to draw on the canvas
  26. self.canvas.bind("<B1-Motion>", self.paint)
  27. def paint(self, event):
  28. """Draw on the canvas by creating ovals (circles) at mouse position."""
  29. x1, y1 = (event.x - self.brush_size), (event.y - self.brush_size)
  30. x2, y2 = (event.x + self.brush_size), (event.y + self.brush_size)
  31. self.canvas.create_oval(x1, y1, x2, y2, fill='black', outline='black')
  32. def clear_canvas(self):
  33. """Clear the canvas to allow the user to draw a new digit."""
  34. self.canvas.delete("all")
  35. def convert_to_array(self):
  36. """Convert the canvas drawing to a 28x28 grayscale array."""
  37. # Get the canvas's pixel data and save it temporarily
  38. x = self.winfo_rootx() + self.canvas.winfo_x()
  39. y = self.winfo_rooty() + self.canvas.winfo_y()
  40. x1 = x + self.canvas.winfo_width()
  41. y1 = y + self.canvas.winfo_height()
  42. # Capture the canvas area and convert it into a grayscale image using PIL
  43. image = ImageGrab.grab((x, y, x1, y1)).convert("L").resize((28, 28), resample=Resampling.HAMMING)
  44. self.demo_image = ImageTk.PhotoImage(image)
  45. self.canvas_demo.create_image(0, 0, anchor=tk.NW, image=self.demo_image)
  46. image_array = np.asarray(image) / 255.0
  47. print(np.array(image_array).reshape((28, 28)))
  48. flat_array = image_array.flatten()
  49. return flat_array