代码import cv2 import numpy as np from PIL import Image, ImageTk import tkinter as tk # 创建白色背景 width = 400 height = 400 img = np.zeros((height, width, 3), np.uint8) img.fill(255) # 在白色背景上绘制圆形 center = (200, 200) radius = 100 color = (0, 0, 255) thickness = 2 cv2.circle(img, center, radius, color, thickness) # 将图像从OpenCV格式转换为PIL格式 img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img_pil = Image.fromarray(img_rgb) # 将PIL图像转换为Tkinter图像 img_tk = ImageTk.PhotoImage(img_pil) # 创建Tkinter窗口并在其中显示图像 root = tk.Tk() label = tk.Label(root, image=img_tk) label.pack() root.mainloop(),出现错误:'PhotoImage' object has no attribute '_PhotoImage__photo'
时间: 2024-03-12 16:45:41 浏览: 68
这个错误可能是由于`PhotoImage`对象被垃圾回收器清除了。你可以尝试使用全局变量来保存`PhotoImage`对象,以防止其被垃圾回收。你可以在代码中添加以下两行代码:
```
global img_tk
img_tk = ImageTk.PhotoImage(img_pil)
```
这样就可以解决这个问题了。
相关问题
import cv2 import numpy as np import pyautogui import tkinter as tk from PIL import ImageTk, Image class WindowDetector: def __init__(self, template_path): self.template = cv2.imread(template_path, 0) self.w, self.h = self.template.shape[::-1] def detect(self): screenshot = pyautogui.screenshot() screenshot = np.array(screenshot) screenshot = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY) res = cv2.matchTemplate(screenshot, self.template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res >= threshold) for pt in zip(*loc[::-1]): cv2.rectangle(screenshot, pt, (pt[0] + self.w, pt[1] + self.h), (0, 0, 255), 2) return screenshot class App: def __init__(self, template_path): self.window_detector = WindowDetector(template_path) self.root = tk.Tk() self.root.title("Window Detector") self.root.geometry("800x600") self.canvas = tk.Canvas(self.root, width=800, height=600) self.canvas.pack() self.template = ImageTk.PhotoImage(Image.open(template_path)) tk.Button(self.root, text="Detect", command=self.detect_window).pack() tk.Label(self.root, image=self.template).pack() self.root.mainloop() def detect_window(self): screenshot = self.window_detector.detect() img = ImageTk.PhotoImage(Image.fromarray(screenshot)) self.canvas.create_image(0, 0, anchor=tk.NW, image=img) self.root.update_idletasks() if __name__ == "__main__": app = App("template.png")
这段代码是用来检测屏幕上是否存在一个特定的窗口,它首先读取一个模板图像,然后使用pyautogui库截取屏幕图像。接着,它使用OpenCV中的模板匹配算法来在屏幕截图中寻找模板图像的匹配位置。如果匹配程度超过了设定的阈值,就会在屏幕截图中标出匹配的位置。最后,它使用tkinter库创建了一个GUI窗口,其中包含一个按钮和一个标签,用户可以点击按钮来检测屏幕上是否存在指定的窗口,并在标签中显示检测结果。
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()
这段代码是一个Python程序,用于画图并识别手写数字。它调用了许多库,如tkinter、cv2、numpy、PIL和tensorflow。程序创建了一个图形用户界面,包括一个白色的画布和一个按钮。用户在画布上绘制数字后,可以点击按钮来触发识别数字的功能。程序会将绘制的数字保存为图片文件,并加载训练好的模型(mnist.h5)来识别数字。程序最后打印出保存的图片文件的坐标信息。
阅读全文