from tkinter import * import cv2 import numpy as np from PIL import ImageGrab from tensorflow.keras.models import load_model from temp import * model = load_model('mnist.h5') image_folder = "img/" root = Tk() root.resizable(0, 0) root.title("HDR") lastx, lasty = None, None image_number = 0 cv = Canvas(root, width=1200, height=480, bg='white') cv.grid(row=0, column=0, pady=2, sticky=W, columnspan=2) def clear_widget(): global cv cv.delete('all') def draw_lines(event): global lastx, lasty x, y = event.x, event.y cv.create_line((lastx, lasty, x, y), width=8, fill='black', capstyle=ROUND, smooth=True, splinesteps=12) lastx, lasty = x, y def activate_event(event): global lastx, lasty cv.bind('<B1-Motion>', draw_lines) lastx, lasty = event.x, event.y cv.bind('<Button-1>', activate_event) def Recognize_Digit(): global image_number filename = f'img_{image_number}.png' root.update() widget = cv x = root.winfo_rootx() + widget.winfo_rootx() y = root.winfo_rooty() + widget.winfo_rooty() x1 = x + widget.winfo_width() y1 = y + widget.winfo_height() print(x, y, x1, y1) # get image and save ImageGrab.grab().crop((x, y, x1, y1)).save(image_folder + filename) image = cv2.imread(image_folder + filename, cv2.IMREAD_COLOR) gray = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2GRAY) ret, th = cv2.threshold( gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) # contours = cv2.findContours( # th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0] Position = findContours(th) for m in range(len(Position)): # make a rectangle box around each curve cv2.rectangle(th, (Position[m][0], Position[m][1]), ( Position[m][2], Position[m][3]), (255, 0, 0), 1) # Cropping out the digit from the image corresponding to the current contours in the for loop digit = th[Position[m][1]:Position[m] [3], Position[m][0]:Position[m][2]] # Resizing that digit to (18, 18) resized_digit = cv2.resize(digit, (18, 18)) # Padding the digit with 5 pixels of black color (zeros) in each side to finally produce the image of (28, 28) padded_digit = np.pad(resized_digit, ((5, 5), (5, 5)), "constant", constant_values=0) digit = padded_digit.reshape(1, 28, 28, 1) digit = digit / 255.0 pred = model.predict([digit])[0] final_pred = np.argmax(pred) data = str(final_pred) + ' ' + str(int(max(pred) * 100)) + '%' print(data) font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 0.5 color = (255, 0, 0) thickness = 1 cv2.putText(th, data, (Position[m][0], Position[m][1] - 5), font, fontScale, color, thickness) cv2.imshow('image', th) cv2.waitKey(0) cv2.destroyAllWindows() btn_save = Button(text='Recognize Digit', command=Recognize_Digit) btn_save.grid(row=2, column=0, pady=1, padx=1) button_clear = Button(text='Clear Widget', command=clear_widget) button_clear.grid(row=2, column=1, pady=1, padx=1) root.mainloop()
时间: 2023-06-06 18:06:05 浏览: 262
这段代码是一个Python程序,用于画图并识别手写数字。它调用了许多库,如tkinter、cv2、numpy、PIL和tensorflow。程序创建了一个图形用户界面,包括一个白色的画布和一个按钮。用户在画布上绘制数字后,可以点击按钮来触发识别数字的功能。程序会将绘制的数字保存为图片文件,并加载训练好的模型(mnist.h5)来识别数字。程序最后打印出保存的图片文件的坐标信息。
相关问题
from sklearn.datasets import load_files from keras.utils import np_utils import numpy as np from glob import glob from keras.preprocessing import image from torch.nn import Dropout from tqdm import tqdm from PIL import ImageFile 如何使用tensorflow2.11.0导入这些库 from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense from tkinter import Tk, Label, Button, filedialog from PIL import ImageTk from tensorflow.keras.callbacks import ModelCheckpoint
在TensorFlow 2.11.0中,您可以使用以下方式导入库:
```python
from sklearn.datasets import load_files
import numpy as np
from glob import glob
from tensorflow.keras.utils import np_utils
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.layers import Dropout
from tqdm import tqdm
from PIL import ImageFile
```
请注意,上述代码中的`keras`被替换为`tensorflow.keras`,因为在TensorFlow 2.x中,`keras`已经成为TensorFlow的一部分,应该使用`tensorflow.keras`模块来访问Keras的功能。
另外,请确保您已经安装了最新版本的TensorFlow(2.11.0)和相关的依赖库。
python tkinter model 花卉分類識別
要使用Python的Tkinter模块实现花卉分类识别,需要使用机器学习模型和图像处理库。以下是一个示例代码,可以演示如何使用机器学习模型和图像处理库对花卉进行分类识别:
```python
import tkinter as tk
import tkinter.filedialog
import tensorflow as tf
import numpy as np
from PIL import Image, ImageTk
# 加载机器学习模型
model = tf.keras.models.load_model("flower_classification.h5")
# 定义花卉类别的名称
class_names = ["daisy", "dandelion", "rose", "sunflower", "tulip"]
class Application:
def __init__(self, window):
self.window = window
self.window.title("花卉分类识别")
# 创建一个Canvas对象用于显示图片
self.canvas = tk.Canvas(window, width=300, height=300)
self.canvas.pack()
# 创建一个按钮用于选择图片
self.btn_browse = tk.Button(window, text="选择图片", command=self.browse_file)
self.btn_browse.pack(anchor=tk.CENTER, expand=True)
# 创建一个标签用于显示识别结果
self.lbl_result = tk.Label(window, text="", font=("Helvetica", 20))
self.lbl_result.pack(anchor=tk.CENTER, expand=True)
self.window.mainloop()
def browse_file(self):
# 打开文件选择对话框
file_path = tkinter.filedialog.askopenfilename()
# 加载图片
image = Image.open(file_path)
image = image.resize((300, 300))
photo = ImageTk.PhotoImage(image)
# 在Canvas对象上显示图片
self.canvas.create_image(0, 0, image=photo, anchor=tk.NW)
# 对图片进行预处理
image = np.array(image) / 255.0
image = np.expand_dims(image, axis=0)
# 对图片进行分类识别
predicted_class = model.predict(image)
predicted_class = np.argmax(predicted_class)
predicted_class = class_names[predicted_class]
# 在标签上显示识别结果
self.lbl_result.config(text=predicted_class)
# 创建GUI界面
Application(tk.Tk())
```
在这个示例代码中,我们使用了一个预训练的机器学习模型进行花卉分类识别。我们首先使用Tkinter的文件选择对话框选择一张图片。然后,我们将图片显示在Canvas对象上,并对图片进行预处理。最后,我们使用机器学习模型对图片进行分类识别,并将结果显示在标签上。
阅读全文