测试帖子
2025-08-07 17:59:30
发布于:浙江
一级标题
二级标题
点赞!!!
云深处机器狗
文件名称为英文!!!
所有文件夹要运行main文件进行文件运行!!!
人脸识别运行操作在帖子最后!
总文件夹:
机器狗的python代码:
文件1:机器狗按键控制
机器狗按键控制文件(看第10行):
import socket
import struct
import tkinter as tk
# 全局变量
server = None
root = None
current_key_label = None
after_id = None
ctrl_addr = ("192.168.2.1", 43893)#机器狗文件地址
def create_gui():
"""创建图形用户界面"""
global root, current_key_label
root = tk.Tk()
root.title("Python代码控制机器狗")
current_key_label = tk.Label(root, text="当前按键:")
# 创建按钮组
button_data = [
("基本状态", [
("心跳(k)", 0x21040001),
("回零(X)", 0x21010C05),
("起立/趴下(Z)", 0x21010202),
("原地模式(L)", 0x21010D05),
("移动模式(C)", 0x21010D06),
]),
("步态", [
("低速(H)", 0x21010300),
("中速(R)", 0x21010307),
("高速(T)", 0x21010303),
("正常/匍匐(Y)", 0x21010406),
("抓地(U)", 0x21010402),
("越障(I)", 0x21010401),
("高踏步(V)", 0x21010407),
]),
("动作", [
("扭身体(1)-静止站立", 0x21010204),
("翻身(2)-趴下", 0x21010205),
("太空步(3)-静止站立", 0x2101030C),
("后空翻(4)-趴下", 0x21010502),
("打招呼(5)-趴下", 0x21010507),
("向前跳(6)-趴下", 0x2101050B),
("扭身跳(7)-静止站立", 0x2101020D),
]),
("移动", [
("前进(W)", 0x21010130, 15000, 0),
("后退(S)", 0x21010130, -15000, 0),
("左平移(A)", 0x21010131, -30000, 0),
("右平移(D)", 0x21010131, 30000, 0),
("左转(Q)", 0x21010135, -32000, 0),
("右转(E)", 0x21010135, 32000, 0),
]),
("模式切换", [
("手动模式(B)", 0x21010C02),
("导航模式(N)", 0x21010C03),
("软急停(P)", 0x21010C0E),
("保存数据", 0x21010C01)
]),
("语音识别", [
("语音-起立", 0x21010C0A, 1, 0),
("语音-坐下", 0x21010C0A, 2, 0),
("语音-前进", 0x21010C0A, 3, 0),
("语音-后退", 0x21010C0A, 4, 0),
("语音-向左平移", 0x21010C0A, 5, 0),
("语音-坐右平移", 0x21010C0A, 6, 0),
("语音-停止", 0x21010C0A, 7, 0),
("语音-打招呼", 0x21010C0A, 22, 0),
("语音-向左看", 0x21010C0A, 11, 0),
("语音-向右看", 0x21010C0A, 12, 0),
("语音-向左转90°", 0x21010C0A, 13, 0),
("语音-向右转90°", 0x21010C0A, 14, 0),
("语音-向后转180°", 0x21010C0A, 15, 0),
])
]
# 创建按钮
button_font = ("黑体", 11)
button_bg_color = "#FFFFFF"
button_active_bg_color = "#FFFACD"
for group_row, (group_name, group_buttons) in enumerate(button_data):
group_frame = tk.LabelFrame(root, text=group_name, font=button_font)
group_frame.grid(row=group_row, column=0,
padx=10, pady=4, sticky="nsew")
for button_col, (text, command, *params) in enumerate(group_buttons):
button = tk.Button(
group_frame,
text=text,
font=button_font,
bg=button_bg_color,
activebackground=button_active_bg_color,
command=lambda cmd=command, p=params: send_command(cmd, *p)
)
button.grid(row=0, column=button_col,
pady=5, padx=4, sticky="nsew")
button.config(fg='black')
# 配置网格布局
for col in range(len(button_data[0][1])):
root.grid_columnconfigure(col, weight=1)
for row in range(len(button_data)):
root.grid_rowconfigure(row, weight=1)
current_key_label.grid(row=len(button_data), column=0, pady=10)
# 绑定键盘事件
root.bind("<KeyPress>", handle_key_press)
root.bind("<KeyRelease>", handle_key_release)
def init_socket(local_port=20001):
"""初始化UDP套接字"""
global server
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
server.bind(("0.0.0.0", local_port))
def send_simple(code, param1=0, param2=0):
"""发送简单命令"""
try:
payload = struct.pack('<3i', code, param1, param2)
server.sendto(payload, ctrl_addr)
except Exception as e:
print(f"发送命令时出错:{e}")
def send_command(code, param1=0, param2=0):
"""发送命令"""
print(f"发送命令:Code={code}, Param1={param1}, Param2={param2}")
send_simple(code, param1, param2)
def continuous_command(code, param1=0, param2=0):
"""连续发送命令"""
send_simple(code, param1, param2)
global after_id
after_id = root.after(100, continuous_command, code, param1, param2)
def start_heartbeat():
"""开始发送心跳指令"""
continuous_command(0x21040001)
def stop_continuous_command():
"""停止连续命令"""
if after_id:
root.after_cancel(after_id)
def handle_key_press(event):
"""处理按键按下事件"""
key_to_command = {
'z': (0x21010202, 0),
'x': (0x21010C05, 0),
'c': (0x21010D06, 0),
'w': (0x21010130, 32767), # 前进
's': (0x21010130, -32767), # 后退
'a': (0x21010131, -32767), # 左平移
'd': (0x21010131, 32767), # 右平移
'q': (0x21010135, -32767), # 左转
'e': (0x21010135, 32767), # 右转
'r': (0x21010307, 0),
't': (0x21010303, 0),
'y': (0x21010406, 0),
'u': (0x21010402, 0),
'i': (0x21010401, 0),
'v': (0x21010407, 0),
'b': (0x21010C02, 0), # 手动
'n': (0x21010C03, 0), # 导航
'p': (0x21010C0E, 0), # 软急停
"l": (0x21010D05, 0), # 原地模式
"h": (0x21010300, 0), # 低速
"1": (0x21010204, 0), # 扭身体
"2": (0x21010205, 0), # 翻身
"3": (0x2101030C, 0), # 太空步
"4": (0x21010502, 0), # 后空翻
"5": (0x21010507, 0), # 打招呼
"6": (0x2101050B, 0), # 向前跳
"7": (0x2101020D, 0) # 扭身跳
}
key = event.char.lower()
if key in key_to_command:
code, param = key_to_command[key]
send_command(code, param)
update_current_key_label(key)
def handle_key_release(event):
"""处理按键释放事件"""
key_to_command = {
'w': (0x21010130, 0), # 停止前进
's': (0x21010130, 0), # 停止后退
'a': (0x21010131, 0), # 停止左平移
'd': (0x21010131, 0), # 停止右平移
'q': (0x21010135, 0), # 停止左转
'e': (0x21010135, 0), # 停止右转
}
key = event.char.lower()
if key in key_to_command:
code, param = key_to_command[key]
send_command(code, param)
update_current_key_label(key)
def update_current_key_label(key):
"""更新当前按键标签"""
current_key_label.config(text=f"当前按键:{key.upper()}")
def on_closing():
"""关闭窗口时的清理工作"""
stop_continuous_command()
server.close()
root.destroy()
def main():
"""主程序"""
init_socket()
create_gui()
start_heartbeat() # 开始发送心跳指令
# 设置关闭窗口时的回调
root.protocol("WM_DELETE_WINDOW", on_closing)
# 运行主循环
root.mainloop()
if __name__ == "__main__":
main()
机器狗摄像头文件:
import cv2
import numpy as np
from PIL import ImageGrab
import tkinter as tk
import threading
from PIL import ImageGrab, ImageDraw # 增加ImageDraw导入
from PIL import Image # 可选,如果涉及更多图像操作
def run():
"""
打开机械狗摄像头(RTSP/RTMP地址),并显示回传画面,
按 Esc 键退出。
"""
cap = cv2.VideoCapture("rtsp://192.168.1.120:8554/test") # 或RTMP地址
print("摄像头对象:", cap)
while True:
ret, frame = cap.read()
if ret:
cv2.imshow('RTSP Stream', frame)
if cv2.waitKey(1) == 27: # 按 Esc 键退出
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
# 使用线程运行机械狗摄像头回传代码,避免阻塞Tkinter界面
t = threading.Thread(target=run, daemon=True)
t.start()
# 启动Tkinter图形界面
#start_tk_interface()
文件2:语音识别
python
上面两个文件和下面一个文件不用管
main文件
rom recording_utils import *
from command import *
GUI()
button1 = tk.Button(root, text="语音识别", command=recognize, width=20, height=3)
button1.place(relx=0.7, rely=0.5, anchor=tk.CENTER)
#起立 趴下 打招呼 后空翻
command文件
#语音识别
from recording_utils import *
from dog import *
#import turtle
#turtle.circle(60)
#from turtle import *
#circle(60)
#from turtle import circle
def recognize():
resurt = recognize_speech("sound.wav")
print(resurt)
#-------------------上面是软件测试----------------------
#连接机器狗
init_socket()
#连接发送心跳(保持接收指令状态)
heart()
#判断指令内容
if "你好" in result:
#满足判断条件
#执行当前动作(调用dog模块)
send_command(0x21010507)
dog文件
import socket
import struct
import tkinter as tk
import threading
# 全局变量
server = None
root = None
current_key_label = None
after_id = None
ctrl_addr = ("192.168.2.1", 43893)
def create_gui():
"""创建图形用户界面"""
global root, current_key_label
root = tk.Tk()
root.title("Python代码控制机器狗")
current_key_label = tk.Label(root, text="当前按键:")
# 创建按钮组
button_data = [
("基本状态", [
("心跳(k)", 0x21040001),
("回零(X)", 0x21010C05),
("起立/趴下(Z)", 0x21010202),
("原地模式(L)", 0x21010D05),
("移动模式(C)", 0x21010D06),
]),
("步态", [
("低速(H)", 0x21010300),
("中速(R)", 0x21010307),
("高速(T)", 0x21010303),
("正常/匍匐(Y)", 0x21010406),
("抓地(U)", 0x21010402),
("越障(I)", 0x21010401),
("高踏步(V)", 0x21010407),
]),
("动作", [
("扭身体(1)-静止站立", 0x21010204),
("翻身(2)-趴下", 0x21010205),
("太空步(3)-静止站立", 0x2101030C),
("后空翻(4)-趴下", 0x21010502),
("打招呼(5)-趴下", 0x21010507),
("向前跳(6)-趴下", 0x2101050B),
("扭身跳(7)-静止站立", 0x2101020D),
]),
("移动", [
("前进(W)", 0x21010130, 15000, 0),
("后退(S)", 0x21010130, -15000, 0),
("左平移(A)", 0x21010131, -30000, 0),
("右平移(D)", 0x21010131, 30000, 0),
("左转(Q)", 0x21010135, -32000, 0),
("右转(E)", 0x21010135, 32000, 0),
]),
("模式切换", [
("手动模式(B)", 0x21010C02),
("导航模式(N)", 0x21010C03),
("软急停(P)", 0x21010C0E),
("保存数据", 0x21010C01)
]),
("语音识别", [
("语音-起立", 0x21010C0A, 1, 0),
("语音-坐下", 0x21010C0A, 2, 0),
("语音-前进", 0x21010C0A, 3, 0),
("语音-后退", 0x21010C0A, 4, 0),
("语音-向左平移", 0x21010C0A, 5, 0),
("语音-坐右平移", 0x21010C0A, 6, 0),
("语音-停止", 0x21010C0A, 7, 0),
("语音-打招呼", 0x21010C0A, 22, 0),
("语音-向左看", 0x21010C0A, 11, 0),
("语音-向右看", 0x21010C0A, 12, 0),
("语音-向左转90°", 0x21010C0A, 13, 0),
("语音-向右转90°", 0x21010C0A, 14, 0),
("语音-向后转180°", 0x21010C0A, 15, 0),
])
]
# 创建按钮
button_font = ("黑体", 11)
button_bg_color = "#FFFFFF"
button_active_bg_color = "#FFFACD"
for group_row, (group_name, group_buttons) in enumerate(button_data):
group_frame = tk.LabelFrame(root, text=group_name, font=button_font)
group_frame.grid(row=group_row, column=0,
padx=10, pady=4, sticky="nsew")
for button_col, (text, command, *params) in enumerate(group_buttons):
button = tk.Button(
group_frame,
text=text,
font=button_font,
bg=button_bg_color,
activebackground=button_active_bg_color,
command=lambda cmd=command, p=params: send_command(cmd, *p)
)
button.grid(row=0, column=button_col,
pady=5, padx=4, sticky="nsew")
button.config(fg='black')
# 配置网格布局
for col in range(len(button_data[0][1])):
root.grid_columnconfigure(col, weight=1)
for row in range(len(button_data)):
root.grid_rowconfigure(row, weight=1)
current_key_label.grid(row=len(button_data), column=0, pady=10)
# 绑定键盘事件
root.bind("<KeyPress>", handle_key_press)
root.bind("<KeyRelease>", handle_key_release)
def init_socket(local_port=20001):
"""初始化UDP套接字"""
global server
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
server.bind(("0.0.0.0", local_port))
def send_simple(code, param1=0, param2=0):
"""发送简单命令"""
try:
payload = struct.pack('<3i', code, param1, param2)
server.sendto(payload, ctrl_addr)
except Exception as e:
print(f"发送命令时出错:{e}")
def send_command(code, param1=0, param2=0):
"""发送命令"""
print(f"发送命令:Code={code}, Param1={param1}, Param2={param2}")
send_simple(code, param1, param2)
def continuous_command(code, param1=0, param2=0):
"""连续发送命令"""
send_simple(code, param1, param2)
global after_id
after_id = root.after(100, continuous_command, code, param1, param2)
def start_heartbeat():
"""开始发送心跳指令"""
continuous_command(0x21040001)
def s():
global timer
send_simple(0x21040001)
timer = threading.Timer(0.1,s)
timer.start()
def heart():
timer = threading.Timer(0.1,s)
timer.start()
def stop_continuous_command():
"""停止连续命令"""
if after_id:
root.after_cancel(after_id)
def handle_key_press(event):
"""处理按键按下事件"""
key_to_command = {
'z': (0x21010202, 0),
'x': (0x21010C05, 0),
'c': (0x21010D06, 0),
'w': (0x21010130, 32767), # 前进
's': (0x21010130, -32767), # 后退
'a': (0x21010131, -32767), # 左平移
'd': (0x21010131, 32767), # 右平移
'q': (0x21010135, -32767), # 左转
'e': (0x21010135, 32767), # 右转
'r': (0x21010307, 0),
't': (0x21010303, 0),
'y': (0x21010406, 0),
'u': (0x21010402, 0),
'i': (0x21010401, 0),
'v': (0x21010407, 0),
'b': (0x21010C02, 0), # 手动
'n': (0x21010C03, 0), # 导航
'p': (0x21010C0E, 0), # 软急停
"l": (0x21010D05, 0), # 原地模式
"h": (0x21010300, 0), # 低速
"1": (0x21010204, 0), # 扭身体
"2": (0x21010205, 0), # 翻身
"3": (0x2101030C, 0), # 太空步
"4": (0x21010502, 0), # 后空翻
"5": (0x21010507, 0), # 打招呼
"6": (0x2101050B, 0), # 向前跳
"7": (0x2101020D, 0) # 扭身跳
}
key = event.char.lower()
if key in key_to_command:
code, param = key_to_command[key]
send_command(code, param)
update_current_key_label(key)
def handle_key_release(event):
"""处理按键释放事件"""
key_to_command = {
'w': (0x21010130, 0), # 停止前进
's': (0x21010130, 0), # 停止后退
'a': (0x21010131, 0), # 停止左平移
'd': (0x21010131, 0), # 停止右平移
'q': (0x21010135, 0), # 停止左转
'e': (0x21010135, 0), # 停止右转
}
key = event.char.lower()
if key in key_to_command:
code, param = key_to_command[key]
send_command(code, param)
update_current_key_label(key)
def update_current_key_label(key):
"""更新当前按键标签"""
current_key_label.config(text=f"当前按键:{key.upper()}")
def on_closing():
"""关闭窗口时的清理工作"""
stop_continuous_command()
server.close()
root.destroy()
'''
def main():
"""主程序"""
init_socket()
create_gui()
start_heartbeat() # 开始发送心跳指令
# 设置关闭窗口时的回调
root.protocol("WM_DELETE_WINDOW", on_closing)
# 运行主循环
root.mainloop()
'''
'''
if __name__ == "__main__":
main()'''
recording_utils文件
import sounddevice as sd
import tkinter as tk
import soundfile as sf
import wave
from vosk import Model, KaldiRecognizer
from tkinter import messagebox
import json
# 全局变量用于控制录制状态
recording = False
outfile = None
stream = None
def callback(indata, frames, time, status):
if status:
print(status)
if recording:
try:
# 将接收到的音频数据写入文件
outfile.write(indata)
except Exception as e:
print(f"写入文件时出错: {e}")
def start_stop_recording():
global recording, outfile, stream
if not recording:
try:
# 定义参数
fs = 44100 # 采样率 44100
channels = 1 # 声道数 1
filename = 'sound.wav' # 保存的文件名
# 打开音频文件以写入数据
outfile = sf.SoundFile(filename, mode='w', samplerate=fs, channels=channels)
# 打开音频流进行实时录制
stream = sd.InputStream(samplerate=fs, channels=channels, callback=callback)
stream.start()
recording = True
print("开始实时录制...")
return "停止录制"
except FileExistsError:
print(f"文件 {filename} 已存在,请删除或更改文件名。")
except Exception as e:
print(f"发生错误: {e}")
return "开始录制"
else:
# 停止录制
if stream:
stream.stop()
stream.close()
if outfile:
outfile.close()
recording = False
print("录制停止。")
return "开始录制"
def recognize_speech(audio_file_path):
"""
此函数用于使用 Vosk 进行语音识别
:param model_path: 语音识别模型的路径
:param audio_file_path: 待识别的音频文件路径
:return: 识别结果字符串
"""
model_path = "model/vosk-model-small-cn-0.22"
# 打开音频文件
try:
wf = wave.open(audio_file_path, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
print("音频文件必须是单声道、16位、无压缩的WAV文件。")
return None
except FileNotFoundError:
print(f"未找到音频文件: {audio_file_path}")
return None
# 创建模型和识别器
model = Model(model_path=model_path)
rec = KaldiRecognizer(model, wf.getframerate())
results = []
# 逐块读取音频数据并进行识别
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
result_dict = json.loads(rec.Result())
results.append(result_dict.get('text',''))
# 输出最终识别结果
final_result_dict = json.loads(rec.FinalResult())
results.append(final_result_dict.get('text', ''))
wf.close()
return ''.join(results)
def perform_recognition(audio_file_path="sound.wav"):
result = recognize_speech(audio_file_path)
if result:
messagebox.showinfo("识别结果", result)
def GUI():
# 创建 Tkinter 窗口
root = tk.Tk()
root.title("声音录制")
# 设置窗口的宽度和高度
window_width = 500
window_height = 300
# 获取屏幕的宽度和高度
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# 计算窗口的起始位置,使窗口居中
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
# 设置窗口的大小和位置
root.geometry(f"{window_width}x{window_height}+{x}+{y}")
# 创建提示文字标签
label = tk.Label(root, text="点击下方按钮开始或停止录制")
label.place(relx=0.5, rely=0.2, anchor=tk.CENTER)
# 创建按钮
button = tk.Button(root, text="开始录制", command=start_stop_recording, width=20, height=3)
# 使用 place 方法将按钮放置在窗口中央
button.place(relx=0.3, rely=0.5, anchor=tk.CENTER)
文件3:颜色识别
只需要三个prthon文件和图片!!!
所有图片要保证是png格式!!!
图片
dog文件:
import socket
import struct
import tkinter as tk
import threading
# 全局变量
server = None
root = None
current_key_label = None
after_id = None
ctrl_addr = ("192.168.2.1", 43893)#地址
def create_gui():
"""创建图形用户界面"""
global root, current_key_label
root = tk.Tk()
root.title("Python代码控制机器狗")
current_key_label = tk.Label(root, text="当前按键:")
# 创建按钮组
button_data = [
("基本状态", [
("心跳(k)", 0x21040001),
("回零(X)", 0x21010C05),
("起立/趴下(Z)", 0x21010202),
("原地模式(L)", 0x21010D05),
("移动模式(C)", 0x21010D06),
]),
("步态", [
("低速(H)", 0x21010300),
("中速(R)", 0x21010307),
("高速(T)", 0x21010303),
("正常/匍匐(Y)", 0x21010406),
("抓地(U)", 0x21010402),
("越障(I)", 0x21010401),
("高踏步(V)", 0x21010407),
]),
("动作", [
("扭身体(1)-静止站立", 0x21010204),
("翻身(2)-趴下", 0x21010205),
("太空步(3)-静止站立", 0x2101030C),
("后空翻(4)-趴下", 0x21010502),
("打招呼(5)-趴下", 0x21010507),
("向前跳(6)-趴下", 0x2101050B),
("扭身跳(7)-静止站立", 0x2101020D),
]),
("移动", [
("前进(W)", 0x21010130, 15000, 0),
("后退(S)", 0x21010130, -15000, 0),
("左平移(A)", 0x21010131, -30000, 0),
("右平移(D)", 0x21010131, 30000, 0),
("左转(Q)", 0x21010135, -32000, 0),
("右转(E)", 0x21010135, 32000, 0),
]),
("模式切换", [
("手动模式(B)", 0x21010C02),
("导航模式(N)", 0x21010C03),
("软急停(P)", 0x21010C0E),
("保存数据", 0x21010C01)
]),
("语音识别", [
("语音-起立", 0x21010C0A, 1, 0),
("语音-坐下", 0x21010C0A, 2, 0),
("语音-前进", 0x21010C0A, 3, 0),
("语音-后退", 0x21010C0A, 4, 0),
("语音-向左平移", 0x21010C0A, 5, 0),
("语音-坐右平移", 0x21010C0A, 6, 0),
("语音-停止", 0x21010C0A, 7, 0),
("语音-打招呼", 0x21010C0A, 22, 0),
("语音-向左看", 0x21010C0A, 11, 0),
("语音-向右看", 0x21010C0A, 12, 0),
("语音-向左转90°", 0x21010C0A, 13, 0),
("语音-向右转90°", 0x21010C0A, 14, 0),
("语音-向后转180°", 0x21010C0A, 15, 0),
])
]
color_btn = tk.Button(root, text="检测颜色", command=check_color_and_act)
color_btn.grid(row=7, column=0, pady=10)
# 创建按钮
button_font = ("黑体", 11)
button_bg_color = "#FFFFFF"
button_active_bg_color = "#FFFACD"
for group_row, (group_name, group_buttons) in enumerate(button_data):
group_frame = tk.LabelFrame(root, text=group_name, font=button_font)
group_frame.grid(row=group_row, column=0,
padx=10, pady=4, sticky="nsew")
for button_col, (text, command, *params) in enumerate(group_buttons):
button = tk.Button(
group_frame,
text=text,
font=button_font,
bg=button_bg_color,
activebackground=button_active_bg_color,
command=lambda cmd=command, p=params: send_command(cmd, *p)
)
button.grid(row=0, column=button_col,
pady=5, padx=4, sticky="nsew")
button.config(fg='black')
# 配置网格布局
for col in range(len(button_data[0][1])):
root.grid_columnconfigure(col, weight=1)
for row in range(len(button_data)):
root.grid_rowconfigure(row, weight=1)
current_key_label.grid(row=len(button_data), column=0, pady=10)
# 绑定键盘事件
root.bind("<KeyPress>", handle_key_press)
root.bind("<KeyRelease>", handle_key_release)
#端口号报错 就改这个函数!!!!!
#ip地址改成自己电脑的--》win+r--》ipconfig--》ipv4
'''
def init_socket(local_port=20000):#端口号在这改
"""初始化UDP套接字"""
global server
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
#把ipv4的值放在这里
server.bind(("192.168.22.234", local_port))
'''
def init_socket(local_port=20001):
"""初始化UDP套接字"""
global server
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
server.bind(("0.0.0.0", local_port))
def send_simple(code, param1=0, param2=0):
"""发送简单命令"""
try:
payload = struct.pack('<3i', code, param1, param2)
server.sendto(payload, ctrl_addr)
except Exception as e:
print(f"发送命令时出错:{e}")
def send_command(code, param1=0, param2=0):
"""发送命令"""
print(f"发送命令:Code={code}, Param1={param1}, Param2={param2}")
send_simple(code, param1, param2)
def continuous_command(code, param1=0, param2=0):
"""连续发送命令"""
send_simple(code, param1, param2)
global after_id
after_id = root.after(100, continuous_command, code, param1, param2)
def start_heartbeat():
"""开始发送心跳指令"""
continuous_command(0x21040001)
def s():
global timer
send_simple(0x21040001)
timer = threading.Timer(0.1,s)
timer.start()
def heart():
timer = threading.Timer(0.1,s)
timer.start()
def stop_continuous_command():
"""停止连续命令"""
if after_id:
root.after_cancel(after_id)
def handle_key_press(event):
"""处理按键按下事件"""
key_to_command = {
'z': (0x21010202, 0),
'x': (0x21010C05, 0),
'c': (0x21010D06, 0),
'w': (0x21010130, 32767), # 前进
's': (0x21010130, -32767), # 后退
'a': (0x21010131, -32767), # 左平移
'd': (0x21010131, 32767), # 右平移
'q': (0x21010135, -32767), # 左转
'e': (0x21010135, 32767), # 右转
'r': (0x21010307, 0),
't': (0x21010303, 0),
'y': (0x21010406, 0),
'u': (0x21010402, 0),
'i': (0x21010401, 0),
'v': (0x21010407, 0),
'b': (0x21010C02, 0), # 手动
'n': (0x21010C03, 0), # 导航
'p': (0x21010C0E, 0), # 软急停
"l": (0x21010D05, 0), # 原地模式
"h": (0x21010300, 0), # 低速
"1": (0x21010204, 0), # 扭身体
"2": (0x21010205, 0), # 翻身
"3": (0x2101030C, 0), # 太空步
"4": (0x21010502, 0), # 后空翻
"5": (0x21010507, 0), # 打招呼
"6": (0x2101050B, 0), # 向前跳
"7": (0x2101020D, 0) # 扭身跳
}
key = event.char.lower()
if key in key_to_command:
code, param = key_to_command[key]
send_command(code, param)
update_current_key_label(key)
def handle_key_release(event):
"""处理按键释放事件"""
key_to_command = {
'w': (0x21010130, 0), # 停止前进
's': (0x21010130, 0), # 停止后退
'a': (0x21010131, 0), # 停止左平移
'd': (0x21010131, 0), # 停止右平移
'q': (0x21010135, 0), # 停止左转
'e': (0x21010135, 0), # 停止右转
}
key = event.char.lower()
if key in key_to_command:
code, param = key_to_command[key]
send_command(code, param)
update_current_key_label(key)
def update_current_key_label(key):
"""更新当前按键标签"""
current_key_label.config(text=f"当前按键:{key.upper()}")
def on_closing():
"""关闭窗口时的清理工作"""
stop_continuous_command()
server.close()
root.destroy()
'''
def main():
"""主程序"""
init_socket()
create_gui()
start_heartbeat() # 开始发送心跳指令
# 设置关闭窗口时的回调
root.protocol("WM_DELETE_WINDOW", on_closing)
# 运行主循环
root.mainloop()
'''
'''
if __name__ == "__main__":
main()'''
main文件
from photo import *
from dog import *
init_socket()
heart()
while(1==1):
r,g,b = grw()
print(r,g,b)
print(max(r,g,b))
if(r<50 and g<50 and b<50):
print("black")
elif(r>200 and g>200 and b>200):
print("white")
elif(max(r,g,b)==r):
print("red")
send_command(0x21010C0A, 2, 0) # 坐下
elif(max(r,g,b)==g):
print("green")
send_command(0x21010C0A, 1, 0) # 起立
elif(max(r,g,b)==b):
print("blue")
send_command(0x21010C0A, 11, 0) # 向左看
#send_command(0x21010C0A, 2, 0) # 坐下
#send_command(0x21010C0A, 1, 0) # 起立
#send_command(0x21010C0A, 11, 0) # 向左看
photo文件
import cv2
import numpy as np
from PIL import ImageGrab
import tkinter as tk
import threading
from PIL import ImageGrab, ImageDraw # 增加ImageDraw导入
from PIL import Image # 可选,如果涉及更多图像操作
#--------打开机械狗摄像头 使画面进行回传 ----
def run():
"""
打开机械狗摄像头(RTSP/RTMP地址),并显示回传画面,
按 Esc 键退出。
"""
cap = cv2.VideoCapture("rtsp://192.168.1.120:8554/test") # 或RTMP地址
print("摄像头对象:", cap)
while True:
ret, frame = cap.read()
# 如需对画面做目标检测,可以将下一行取消注释
# frame = detect_traffic_light(frame)
if ret:
cv2.imshow('RTSP Stream', frame)
if cv2.waitKey(1) == 27: # 按 Esc 键退出
break
cap.release()
cv2.destroyAllWindows()
def grw():
"""
1) 启动 run() 线程,显示摄像头回传
2) 弹出 Tk 窗口,点击“拍照”按钮后:
- 截屏 (0,0)-(1930,1110)
- 画十字、框、保存图片
- 打印并返回 "R,G,B"
"""
# ---- 第一步:启动摄像头回传线程 ----
t = threading.Thread(target=run, daemon=True)
t.start()
"""
弹出Tkinter图形界面,点击“拍照”按钮后:
1. 截图左上角到(1930,1110)
2. 画十字和绿色方框
3. 保存截图
4. 打印中心像素RGB值
5. 打印平均RGB值
6. 返回字符串 "R,G,B"
"""
root = tk.Tk()
root.title("截屏工具")
root.geometry("300x100")
result = {"rgb": None}
def on_click():
# 截图区域
screenshot = ImageGrab.grab(bbox=(0, 0, 1930, 1110))
draw_img = screenshot.copy()
draw = ImageDraw.Draw(draw_img)
width, height = screenshot.size
sample_size = 100
half_size = sample_size // 2
cx, cy = width // 2, height // 2
# 红色十字线
draw.line((cx - 30, cy, cx + 30, cy), fill=(255, 0, 0), width=2)
draw.line((cx, cy - 30, cx, cy + 30), fill=(255, 0, 0), width=2)
# 绿色方框
draw.rectangle((cx - half_size, cy - half_size, cx + half_size, cy + half_size), outline=(0, 255, 0),
width=2)
draw_img.save("screenshot_with_marker.png", "PNG")
img_np = np.array(screenshot)
roi = img_np[cy - half_size:cy + half_size, cx - half_size:cx + half_size]
pixels = roi.reshape((-1, 3))
# #print("\n中心区域前10个像素的RGB值:")
# for i in range(90, 100):
# print(f"像素{i + 1}: {pixels[i]}")
avg_r = np.mean(pixels[:, 0])
avg_g = np.mean(pixels[:, 1])
avg_b = np.mean(pixels[:, 2])
avg_color = np.array([avg_r, avg_g, avg_b]).astype(int)
R_r = int(avg_r)
G_g = int(avg_g)
B_b = int(avg_b)
#rgb_str = [,,]
#rgb_str = "{},{},{}".format(int(avg_r), int(avg_g), int(avg_b))
# print(f"\n中心区域({sample_size}x{sample_size})平均RGB值:", tuple(avg_color))
#print("实际采样像素数量:", len(pixels))
# print(rgb_str)
print('中心区域平均RGB为:',R_r, G_g, B_b)
#print('红色数值(变量名:R_r)',R_r)
#print('绿色数值(变量名:G_g)', G_g)
#print('蓝色数值(变量名:B_b)', B_b)
#result["rgb"] = rgb_str
result["rgb"] = R_r,G_g,B_b
root.destroy()
btn = tk.Button(root, text="拍照", font=("Arial", 14), command=on_click)
btn.pack(padx=20, pady=20)
root.mainloop()
return result["rgb"]
if __name__ == "__main__":
# 使用线程运行机械狗摄像头回传代码,避免阻塞Tkinter界面
t = threading.Thread(target=run, daemon=True)
t.start()
# 启动Tkinter图形界面
#start_tk_interface()
grw()
文件4:群体机器人控制
student_action文件
def student_action(root, send_command, start_heartbeat, stop_continuous_command):
send_command(0x21010202)
root.after(5000,lambda:send_command(0x2101020D))
root.after(5000+4300,lambda:send_command(0x21010507))
root.after(5000+4300+11000,lambda:send_command(0x2101020D))
root.after(5000+4300+11000+4300,lambda:send_command(0x21010521))
root.after(5000+4300+11000+4300+67000,lambda:send_command(0x2101020D))
root.after(5000+4300+11000+4300+67000+4300,lambda:send_command(0x2101050B))
root.after(5000+4300+11000+4300+67000+4300+6000,lambda:send_command(0x2101020D))
root.after(5000+4300+11000+4300+67000+4300+6000+4300,lambda:send_command(0x21010522))
root.after(5000+4300+11000+4300+67000+4300+6000+4300+63788,lambda:send_command(0x21010507))
start_heartbeat()
计时器文件
import tkinter as tk
import time
class TimerApp:
def __init__(self):
self.root = tk.Tk()
self.root.title("秒表计时器")
self.root.geometry("1200x800") # 可选:放大窗口
# 显示标签
self.label = tk.Label(self.root, text="0.140 s", font=("Arial", 144))
self.label.pack(padx=150, pady=(60, 30))
# 按钮框架
btn_frame = tk.Frame(self.root)
btn_frame.pack(pady=(0, 60))
# 三个按钮宽度和字体
btn_width = 30
btn_font = ("Arial", 36)
# 开始按钮(第一行)
self.start_btn = tk.Button(
btn_frame, text="开始", width=btn_width, font=btn_font,
command=self.start
)
self.start_btn.grid(row=0, column=0, padx=15, pady=10, sticky="ew")
# 暂停按钮(第二行)
self.pause_btn = tk.Button(
btn_frame, text="暂停", width=btn_width, font=btn_font,
command=self.pause, state="disabled"
)
self.pause_btn.grid(row=1, column=0, padx=15, pady=10, sticky="ew")
# 回零按钮(第三行)
self.reset_btn = tk.Button(
btn_frame, text="回零", width=btn_width, font=btn_font,
command=self.reset, state="disabled"
)
self.reset_btn.grid(row=2, column=0, padx=15, pady=10, sticky="ew")
# 控制变量
self.running = False
self.start_time = 0.0
self.elapsed = 0.0
# 启动更新循环
self.update()
self.root.mainloop()
def start(self):
"""开始计时"""
if not self.running:
self.start_time = time.time() - self.elapsed
self.running = True
self.start_btn.config(state="disabled")
self.pause_btn.config(state="normal")
self.reset_btn.config(state="normal")
def pause(self):
"""暂停计时"""
if self.running:
self.running = False
self.elapsed = time.time() - self.start_time
self.start_btn.config(state="normal")
self.pause_btn.config(state="disabled")
def reset(self):
"""回零并准备重新开始"""
self.running = False
self.elapsed = 0.0
self.label.config(text="0.000 s")
self.start_btn.config(state="normal")
self.pause_btn.config(state="disabled")
self.reset_btn.config(state="disabled")
def update(self):
"""定时更新显示(每 10 ms)"""
if self.running:
current = time.time() - self.start_time
else:
current = self.elapsed
self.label.config(text=f"{current:.3f} s")
self.root.after(10, self.update)
if __name__ == "__main__":
TimerApp()
组合动作按键主代码文件
import socket
import struct
import tkinter as tk
# 添加在文件开头
from student_action import student_action # 导入学生写的组合动作
# 全局变量
server = None
root = None
current_key_label = None
after_id = None
ctrl_addr = ("192.168.2.1", 43893)
def create_gui():
"""创建图形用户界面"""
global root, current_key_label
root = tk.Tk()
root.title("Python代码控制机器狗")
current_key_label = tk.Label(root, text="当前按键:")
# 创建按钮组
button_data = [
("基本状态", [
("心跳", 0x21040001),
("回零", 0x21010C05),
("起立/趴下", 0x21010202),
("原地模式", 0x21010D05),
("移动模式", 0x21010D06),
]),
("步态", [
("低速", 0x21010300),
("中速", 0x21010307),
("正常/匍匐", 0x21010406),
("越障", 0x21010401),
("高踏步", 0x21010407),
]),
("动作", [
("扭身体", 0x21010204),
#("太空步", 0x2101030C),
("后空翻", 0x21010502),
("打招呼", 0x21010507),
("向前跳", 0x2101050B),
("扭身跳", 0x2101020D),
("舞蹈1", 0x21010521),
("舞蹈2", 0x21010522)
]),#("太空步", 0x2101030C),
("移动", [
("前进(W)", 0x21010130, 15000, 0),
("后退(S)", 0x21010130, -15000, 0),
("左平移(A)", 0x21010131, -30000, 0),
("右平移(D)", 0x21010131, 30000, 0),
("左转(Q)", 0x21010135, -32000, 0),
("右转(E)", 0x21010135, 32000, 0),
]),
("高级控制", [
# 使用元组明确标识函数类型命令
("组合动作(G)", "func", action_combination)
])
]#高级控制 19:28
# 创建按钮
button_font = ("黑体", 11)
button_bg_color = "#FFFFFF"
button_active_bg_color = "#FFFACD"
for group_row, (group_name, group_buttons) in enumerate(button_data):
group_frame = tk.LabelFrame(root, text=group_name, font=button_font)
group_frame.grid(row=group_row, column=0,
padx=10, pady=4, sticky="nsew")
for button_col, btn_info in enumerate(group_buttons):
if len(btn_info) == 3 and btn_info[1] == "func":
text, _, func = btn_info
button = tk.Button(
group_frame,
text=text,
font=button_font,
bg=button_bg_color,
activebackground=button_active_bg_color,
command=func # 直接传函数引用,不加括号
)
else:
text, command, *params = btn_info
button = tk.Button(
group_frame,
text=text,
font=button_font,
bg=button_bg_color,
activebackground=button_active_bg_color,
command=lambda cmd=command, p=params: send_command(cmd, *p)
)
button.grid(row=0, column=button_col, pady=5, padx=4, sticky="nsew")
button.config(fg='black')
# 配置网格布局
for col in range(len(button_data[0][1])):
root.grid_columnconfigure(col, weight=1)
for row in range(len(button_data)):
root.grid_rowconfigure(row, weight=1)
current_key_label.grid(row=len(button_data), column=0, pady=10)
# 绑定键盘事件
root.bind("<KeyPress>", handle_key_press)
root.bind("<KeyRelease>", handle_key_release)
def init_socket(local_port=20001):
"""初始化UDP套接字"""
global server
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
server.bind(("0.0.0.0", local_port))
def send_simple(code, param1=0, param2=0):
"""发送简单命令"""
try:
payload = struct.pack('<3i', code, param1, param2)
server.sendto(payload, ctrl_addr)
except Exception as e:
print(f"发送命令时出错:{e}")
def send_command(code, param1=0, param2=0):
"""发送命令"""
print(f"发送命令:Code={code}, Param1={param1}, Param2={param2}")
send_simple(code, param1, param2)
def continuous_command(code, param1=0, param2=0):
"""连续发送命令"""
send_simple(code, param1, param2)
global after_id
after_id = root.after(100, continuous_command, code, param1, param2)
def start_heartbeat():
"""开始发送心跳指令"""
continuous_command(0x21040001)
def stop_continuous_command():
"""停止连续命令"""
if after_id:
root.after_cancel(after_id)
def handle_key_press(event):
"""处理按键按下事件"""
key_to_command = {
'z': (0x21010202, 0),
'x': (0x21010C05, 0),
'c': (0x21010D06, 0),
'w': (0x21010130, 32767), # 前进
's': (0x21010130, -32767), # 后退
'a': (0x21010131, -32767), # 左平移
'd': (0x21010131, 32767), # 右平移
'q': (0x21010135, -32767), # 左转
'e': (0x21010135, 32767), # 右转
'r': (0x21010307, 0),
't': (0x21010303, 0),
'y': (0x21010406, 0),
'u': (0x21010402, 0),
'i': (0x21010401, 0),
'v': (0x21010407, 0),
'b': (0x21010C02, 0), # 手动
'n': (0x21010C03, 0), # 导航
'p': (0x21010C0E, 0), # 软急停
"l": (0x21010D05, 0), # 原地模式
"h": (0x21010300, 0), # 低速
"1": (0x21010204, 0), # 扭身体
"2": (0x21010205, 0), # 翻身
"3": (0x2101030C, 0), # 太空步
"4": (0x21010502, 0), # 后空翻
"5": (0x21010507, 0), # 打招呼
"6": (0x2101050B, 0), # 向前跳
"7": (0x2101020D, 0), # 扭身跳
'g': ("func", action_combination) # G键触发组合动作
}
key = event.char.lower()
if key in key_to_command:
#19:32
cmd_type, cmd = key_to_command[key]
if cmd_type == "func":
cmd() # 直接执行函数
else:
send_command(cmd)
def handle_key_release(event):
"""处理按键释放事件"""
key_to_command = {
'w': (0x21010130, 0), # 停止前进
's': (0x21010130, 0), # 停止后退
'a': (0x21010131, 0), # 停止左平移
'd': (0x21010131, 0), # 停止右平移
'q': (0x21010135, 0), # 停止左转
'e': (0x21010135, 0), # 停止右转
}
key = event.char.lower()
if key in key_to_command:
code, param = key_to_command[key]
send_command(code, param)
update_current_key_label(key)
#学生代码完成区
def action_combination():
# 调用学生写的组合动作,传入需要的变量
student_action(root, send_command, start_heartbeat, stop_continuous_command)
def update_current_key_label(key):
"""更新当前按键标签"""
current_key_label.config(text=f"当前按键:{key.upper()}")
def on_closing():
"""关闭窗口时的清理工作"""
stop_continuous_command()
server.close()
root.destroy()
def main():
"""主程序"""
init_socket()
create_gui()
start_heartbeat() # 开始发送心跳指令
# 设置关闭窗口时的回调
root.protocol("WM_DELETE_WINDOW", on_closing)
# 运行主循环
root.mainloop()
if __name__ == "__main__":
main()
文件5:人脸识别
所有图片要保证是jpg格式!!!
man1图片
man2图片
man3图片
woman1图片
woman2图片
main文件
from face import *
p1 = input()
img1 = change(p1)
p2=input()
img2 = change(p2)
s=facial_comparison(img1,img2)
print(s)
dog文件
import socket
import struct
import tkinter as tk
import threading
# 全局变量
server = None
root = None
current_key_label = None
after_id = None
ctrl_addr = ("192.168.2.1", 43893)
def create_gui():
"""创建图形用户界面"""
global root, current_key_label
root = tk.Tk()
root.title("Python代码控制机器狗")
current_key_label = tk.Label(root, text="当前按键:")
# 创建按钮组
button_data = [
("基本状态", [
("心跳(k)", 0x21040001),
("回零(X)", 0x21010C05),
("起立/趴下(Z)", 0x21010202),
("原地模式(L)", 0x21010D05),
("移动模式(C)", 0x21010D06),
]),
("步态", [
("低速(H)", 0x21010300),
("中速(R)", 0x21010307),
("高速(T)", 0x21010303),
("正常/匍匐(Y)", 0x21010406),
("抓地(U)", 0x21010402),
("越障(I)", 0x21010401),
("高踏步(V)", 0x21010407),
]),
("动作", [
("扭身体(1)-静止站立", 0x21010204),
("翻身(2)-趴下", 0x21010205),
("太空步(3)-静止站立", 0x2101030C),
("后空翻(4)-趴下", 0x21010502),
("打招呼(5)-趴下", 0x21010507),
("向前跳(6)-趴下", 0x2101050B),
("扭身跳(7)-静止站立", 0x2101020D),
]),
("移动", [
("前进(W)", 0x21010130, 15000, 0),
("后退(S)", 0x21010130, -15000, 0),
("左平移(A)", 0x21010131, -30000, 0),
("右平移(D)", 0x21010131, 30000, 0),
("左转(Q)", 0x21010135, -32000, 0),
("右转(E)", 0x21010135, 32000, 0),
]),
("模式切换", [
("手动模式(B)", 0x21010C02),
("导航模式(N)", 0x21010C03),
("软急停(P)", 0x21010C0E),
("保存数据", 0x21010C01)
]),
("语音识别", [
("语音-起立", 0x21010C0A, 1, 0),
("语音-坐下", 0x21010C0A, 2, 0),
("语音-前进", 0x21010C0A, 3, 0),
("语音-后退", 0x21010C0A, 4, 0),
("语音-向左平移", 0x21010C0A, 5, 0),
("语音-坐右平移", 0x21010C0A, 6, 0),
("语音-停止", 0x21010C0A, 7, 0),
("语音-打招呼", 0x21010C0A, 22, 0),
("语音-向左看", 0x21010C0A, 11, 0),
("语音-向右看", 0x21010C0A, 12, 0),
("语音-向左转90°", 0x21010C0A, 13, 0),
("语音-向右转90°", 0x21010C0A, 14, 0),
("语音-向后转180°", 0x21010C0A, 15, 0),
])
]
# 创建按钮
button_font = ("黑体", 11)
button_bg_color = "#FFFFFF"
button_active_bg_color = "#FFFACD"
for group_row, (group_name, group_buttons) in enumerate(button_data):
group_frame = tk.LabelFrame(root, text=group_name, font=button_font)
group_frame.grid(row=group_row, column=0,
padx=10, pady=4, sticky="nsew")
for button_col, (text, command, *params) in enumerate(group_buttons):
button = tk.Button(
group_frame,
text=text,
font=button_font,
bg=button_bg_color,
activebackground=button_active_bg_color,
command=lambda cmd=command, p=params: send_command(cmd, *p)
)
button.grid(row=0, column=button_col,
pady=5, padx=4, sticky="nsew")
button.config(fg='black')
# 配置网格布局
for col in range(len(button_data[0][1])):
root.grid_columnconfigure(col, weight=1)
for row in range(len(button_data)):
root.grid_rowconfigure(row, weight=1)
current_key_label.grid(row=len(button_data), column=0, pady=10)
# 绑定键盘事件
root.bind("<KeyPress>", handle_key_press)
root.bind("<KeyRelease>", handle_key_release)
def init_socket(local_port=20001):
"""初始化UDP套接字"""
global server
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
server.bind(("0.0.0.0", local_port))
def send_simple(code, param1=0, param2=0):
"""发送简单命令"""
try:
payload = struct.pack('<3i', code, param1, param2)
server.sendto(payload, ctrl_addr)
except Exception as e:
print(f"发送命令时出错:{e}")
def send_command(code, param1=0, param2=0):
"""发送命令"""
print(f"发送命令:Code={code}, Param1={param1}, Param2={param2}")
send_simple(code, param1, param2)
def continuous_command(code, param1=0, param2=0):
"""连续发送命令"""
send_simple(code, param1, param2)
global after_id
after_id = root.after(100, continuous_command, code, param1, param2)
def start_heartbeat():
"""开始发送心跳指令"""
continuous_command(0x21040001)
def s():
global timer
send_simple(0x21040001)
timer = threading.Timer(0.1,s)
timer.start()
def heart():
timer = threading.Timer(0.1,s)
timer.start()
def stop_continuous_command():
"""停止连续命令"""
if after_id:
root.after_cancel(after_id)
def handle_key_press(event):
"""处理按键按下事件"""
key_to_command = {
'z': (0x21010202, 0),
'x': (0x21010C05, 0),
'c': (0x21010D06, 0),
'w': (0x21010130, 32767), # 前进
's': (0x21010130, -32767), # 后退
'a': (0x21010131, -32767), # 左平移
'd': (0x21010131, 32767), # 右平移
'q': (0x21010135, -32767), # 左转
'e': (0x21010135, 32767), # 右转
'r': (0x21010307, 0),
't': (0x21010303, 0),
'y': (0x21010406, 0),
'u': (0x21010402, 0),
'i': (0x21010401, 0),
'v': (0x21010407, 0),
'b': (0x21010C02, 0), # 手动
'n': (0x21010C03, 0), # 导航
'p': (0x21010C0E, 0), # 软急停
"l": (0x21010D05, 0), # 原地模式
"h": (0x21010300, 0), # 低速
"1": (0x21010204, 0), # 扭身体
"2": (0x21010205, 0), # 翻身
"3": (0x2101030C, 0), # 太空步
"4": (0x21010502, 0), # 后空翻
"5": (0x21010507, 0), # 打招呼
"6": (0x2101050B, 0), # 向前跳
"7": (0x2101020D, 0) # 扭身跳
}
key = event.char.lower()
if key in key_to_command:
code, param = key_to_command[key]
send_command(code, param)
update_current_key_label(key)
def handle_key_release(event):
"""处理按键释放事件"""
key_to_command = {
'w': (0x21010130, 0), # 停止前进
's': (0x21010130, 0), # 停止后退
'a': (0x21010131, 0), # 停止左平移
'd': (0x21010131, 0), # 停止右平移
'q': (0x21010135, 0), # 停止左转
'e': (0x21010135, 0), # 停止右转
}
key = event.char.lower()
if key in key_to_command:
code, param = key_to_command[key]
send_command(code, param)
update_current_key_label(key)
def update_current_key_label(key):
"""更新当前按键标签"""
current_key_label.config(text=f"当前按键:{key.upper()}")
def on_closing():
"""关闭窗口时的清理工作"""
stop_continuous_command()
server.close()
root.destroy()
'''
def main():
"""主程序"""
init_socket()
create_gui()
start_heartbeat() # 开始发送心跳指令
# 设置关闭窗口时的回调
root.protocol("WM_DELETE_WINDOW", on_closing)
# 运行主循环
root.mainloop()
'''
'''
if __name__ == "__main__":
main()'''
face文件
import cv2
import numpy as np
from numpy.linalg import norm
net = cv2.dnn.readNetFromTorch("models/nn4.small2.v1.t7")
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
def extract_features(face_img):
"""提取128维特征向量"""
blob = cv2.dnn.blobFromImage(face_img, 1.0/255, (96, 96), (0, 0, 0), swapRB=True)
net.setInput(blob)
return net.forward().flatten()
def facial_comparison(img1, img2):
"""计算余弦相似度"""
feat1 = extract_features(img1)
feat2 = extract_features(img2)
similarity = np.dot(feat1, feat2) / (norm(feat1) * norm(feat2))
return float(similarity)
def change(path):
face = cv2.imread(path)
return face
机器狗拍摄照片和人脸识别文件(这个是人脸识别文件里面的!)
全部评论 1
一级标题
二级标题云深处机器狗
文件名称为英文!!!
总文件夹:文件1:机器狗按键控制
机器狗按键控制文件(看第10行):
import socket
import struct
import tkinter as tk全局变量
server = None
root = None
current_key_label = None
after_id = None
ctrl_addr = ("192.168.2.1", 43893)#机器狗文件地址def create_gui():
"""创建图形用户界面"""
global root, current_key_labelroot = tk.Tk() root.title("Python代码控制机器狗") current_key_label = tk.Label(root, text="当前按键:") # 创建按钮组 button_data = [ ("基本状态", [ ("心跳(k)", 0x21040001), ("回零(X)", 0x21010C05), ("起立/趴下(Z)", 0x21010202), ("原地模式(L)", 0x21010D05), ("移动模式(C)", 0x21010D06), ]), ("步态", [ ("低速(H)", 0x21010300), ("中速(R)", 0x21010307), ("高速(T)", 0x21010303), ("正常/匍匐(Y)", 0x21010406), ("抓地(U)", 0x21010402), ("越障(I)", 0x21010401), ("高踏步(V)", 0x21010407), ]), ("动作", [ ("扭身体(1)-静止站立", 0x21010204), ("翻身(2)-趴下", 0x21010205), ("太空步(3)-静止站立", 0x2101030C), ("后空翻(4)-趴下", 0x21010502), ("打招呼(5)-趴下", 0x21010507), ("向前跳(6)-趴下", 0x2101050B), ("扭身跳(7)-静止站立", 0x2101020D), ]), ("移动", [ ("前进(W)", 0x21010130, 15000, 0), ("后退(S)", 0x21010130, -15000, 0), ("左平移(A)", 0x21010131, -30000, 0), ("右平移(D)", 0x21010131, 30000, 0), ("左转(Q)", 0x21010135, -32000, 0), ("右转(E)", 0x21010135, 32000, 0), ]), ("模式切换", [ ("手动模式(B)", 0x21010C02), ("导航模式(N)", 0x21010C03), ("软急停(P)", 0x21010C0E), ("保存数据", 0x21010C01) ]), ("语音识别", [ ("语音-起立", 0x21010C0A, 1, 0), ("语音-坐下", 0x21010C0A, 2, 0), ("语音-前进", 0x21010C0A, 3, 0), ("语音-后退", 0x21010C0A, 4, 0), ("语音-向左平移", 0x21010C0A, 5, 0), ("语音-坐右平移", 0x21010C0A, 6, 0),
4天前 来自 浙江
0?
4天前 来自 浙江
0
有帮助,赞一个