上图先
# -*- coding: utf-8 -*- import cv2 import mediapipe as mp import numpy as np import time import sys import os import tempfile import subprocess # 解决中文显示问题 - 使用Pillow确保中文正确显示 def cv2_puttext_chinese(img, text, position, font_scale, color, thickness): """ 使用Pillow库在OpenCV图像上显示中文 """ try: from PIL import Image, ImageDraw, ImageFont # 确保颜色格式正确 if isinstance(color, tuple) and len(color) == 3: # OpenCV是BGR格式,需要转换为RGB color_rgb = (color[2], color[1], color[0]) else: color_rgb = (255, 255, 255) # 将OpenCV图像转换为PIL图像 img_pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img_pil) # 确定字体大小 font_size = int(font_scale * 20) # 调整比例以匹配cv2.putText # 尝试使用系统中常见的中文字体 font_paths = [ "C:/Windows/Fonts/simhei.ttf", # 黑体 "C:/Windows/Fonts/msyh.ttc", # 微软雅黑 "C:/Windows/Fonts/msyhbd.ttc", # 微软雅黑粗体 "C:/Windows/Fonts/simsun.ttc", # 宋体 "C:/Windows/Fonts/arial.ttf", # 英文备选 ] font = None for font_path in font_paths: try: if os.path.exists(font_path): font = ImageFont.truetype(font_path, font_size) break except Exception: continue # 如果没有找到合适的字体,使用默认字体 if font is None: font = ImageFont.load_default() # 绘制中文文本 draw.text(position, text, font=font, fill=color_rgb) # 转换回OpenCV格式 img = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR) return img except ImportError: # 如果PIL不可用,使用简单的英文替代 english_map = { "右手抹鼻子": "Right hand to nose", "左手摸头发": "Left hand to hair", "双手击掌": "Hands clap", "SOP完成!": "SOP Complete!", "剩余时间": "Time left", "秒": "s" } for chinese, english in english_map.items(): text = text.replace(chinese, english) cv2.putText(img, text, position, cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, thickness, cv2.LINE_AA) return img except Exception as e: # 其他错误情况下,使用英文替代 english_map = { "右手抹鼻子": "Right hand to nose", "左手摸头发": "Left hand to hair", "双手击掌": "Hands clap", "SOP完成!": "SOP Complete!", "剩余时间": "Time left", "秒": "s" } for chinese, english in english_map.items(): text = text.replace(chinese, english) cv2.putText(img, text, position, cv2.FONT_HERSHEY_SIMPLEX,