You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

摄像头人脸跟踪舵机控制Python程序运行报错:pyserial TypeError: unicode strings are not supported, please encode to bytes

解决Python人脸跟踪舵机程序的串口错误及坐标计算问题

错误原因分析

你遇到的TypeError: unicode strings are not supported, please encode to bytes非常明确:PySerial库的write()方法只接受字节(bytes)类型数据,但你传入的是普通字符串(str)类型的data变量,这就导致了类型不匹配的崩溃。

另外,你的代码里还有一个容易被忽略的逻辑错误——人脸中心坐标的计算公式写错了,这会导致舵机跟踪的位置不准确。

具体修复步骤

  1. 将字符串编码为字节后发送
    在调用arduino.write()时,通过encode()方法把字符串转换成字节格式,推荐使用UTF-8编码:

    arduino.write(data.encode('utf-8'))
    
  2. 修正人脸中心坐标计算逻辑
    当前代码里的中心计算公式混淆了宽度(w)和高度(h):

    xx = int(x+(x+h))/2  # 错误:误用了高度h来计算x方向中心
    yy = int(y+(y+w))/2  # 错误:误用了宽度w来计算y方向中心
    

    正确的计算应该是:人脸左上角坐标(x,y)加上对应方向尺寸的一半,即:

    xx = x + w / 2  # x方向中心 = 左上角x + 宽度的一半
    yy = y + h / 2  # y方向中心 = 左上角y + 高度的一半
    

修改后的核心代码片段

for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 5)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    arr = {y: y+h, x: x+w}
    print(arr)
    print('X :' + str(x))
    print('Y :'+str(y))
    print('x+w :' + str(x+w))
    print('y+h :' + str(y+h))
    # 修正后的中心坐标计算
    xx = x + w / 2
    yy = y + h / 2
    print(xx)
    print(yy)
    center = (xx, yy)
    print("Center of Rectangle is :", center)
    data = "X{0:f}Y{1:f}Z".format(xx, yy)
    print("output = '" + data + "'")
    # 编码为字节后发送到串口
    arduino.write(data.encode('utf-8'))

额外优化建议

  • 可以在发送数据后添加短延时(比如time.sleep(0.05)),避免串口数据发送过于密集导致Arduino处理不过来。
  • 确认Arduino端代码能正确解析XxxxxxYyyyyyZ格式的数据,比如通过字符串分割提取X、Y数值后再控制舵机。

内容的提问来源于stack exchange,提问作者user16486451

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 19:47:37