- 新增 jiyi.py 文件,实现字母翻牌记忆游戏功能 - 添加 youxijiemian.py 文件,创建游戏开始界面 - 使用 turtle 和 tkinter 模块分别实现游戏和界面 - 支持选择不同难度的游戏模式
76 lines
2.4 KiB
Python
76 lines
2.4 KiB
Python
import cv2
|
|
import tkinter as tk
|
|
from tkinter import messagebox
|
|
from PIL import Image, ImageTk
|
|
from aip import AipImageClassify
|
|
import tempfile
|
|
|
|
# 百度API信息
|
|
APP_ID = '118721834'
|
|
API_KEY = 'ib9k87nafhhLc8yHJh8mToXA'
|
|
SECRET_KEY = 'PJsKue6TCMsTHWjtKtCRI25onh4YfZ5j'
|
|
|
|
client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)
|
|
|
|
# 识别函数
|
|
def recognize_image(image_path):
|
|
with open(image_path, 'rb') as f:
|
|
img_data = f.read()
|
|
result = client.advancedGeneral(img_data)
|
|
if 'result' in result:
|
|
return [(i['keyword'], i['score']) for i in result['result'] if i['score'] >= 0.6]
|
|
else:
|
|
return [("识别失败", 0.0)]
|
|
|
|
# UI类
|
|
class CameraApp:
|
|
def __init__(self, window):
|
|
self.window = window
|
|
self.window.title("拍照识别 - 百度AI")
|
|
self.video_capture = cv2.VideoCapture(0)
|
|
|
|
self.canvas = tk.Canvas(window, width=640, height=480)
|
|
self.canvas.pack()
|
|
|
|
self.btn = tk.Button(window, text="📸 拍照识别", command=self.capture_and_recognize)
|
|
self.btn.pack(pady=10)
|
|
|
|
self.result_label = tk.Label(window, text="", font=("微软雅黑", 12))
|
|
self.result_label.pack()
|
|
|
|
self.update_video()
|
|
|
|
def update_video(self):
|
|
ret, frame = self.video_capture.read()
|
|
if ret:
|
|
self.current_frame = frame
|
|
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
|
img = Image.fromarray(cv2image)
|
|
imgtk = ImageTk.PhotoImage(image=img)
|
|
self.canvas.create_image(0, 0, anchor=tk.NW, image=imgtk)
|
|
self.canvas.imgtk = imgtk
|
|
self.window.after(30, self.update_video)
|
|
|
|
def capture_and_recognize(self):
|
|
if hasattr(self, 'current_frame'):
|
|
with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp:
|
|
img_path = tmp.name
|
|
cv2.imwrite(img_path, self.current_frame)
|
|
|
|
results = recognize_image(img_path)
|
|
if results:
|
|
text = "\n".join([f"✅ {k} ({score*100:.1f}%)" for k, score in results])
|
|
self.result_label.config(text=text)
|
|
else:
|
|
self.result_label.config(text="❌ 无法识别")
|
|
|
|
def __del__(self):
|
|
if self.video_capture.isOpened():
|
|
self.video_capture.release()
|
|
|
|
# 启动应用
|
|
if __name__ == '__main__':
|
|
root = tk.Tk()
|
|
app = CameraApp(root)
|
|
root.mainloop()
|