重现步骤
将代码文件保存后脱机运行不起来,其他文件可以,不脱机可正常运行
期待结果和实际结果
能正常脱机使用
软硬件版本信息
错误日志
尝试解决过程
补充材料
重现步骤
将代码文件保存后脱机运行不起来,其他文件可以,不脱机可正常运行
期待结果和实际结果
能正常脱机使用
软硬件版本信息
错误日志
尝试解决过程
补充材料
import time, os, sys
from machine import UART
from machine import FPIOA
from media.sensor import *
from media.display import *
from media.media import *
import utime
from machine import Pin
fpioa = FPIOA()
fpioa.set_function(11, FPIOA.UART2_TXD)
fpioa.set_function(12, FPIOA.UART2_RXD)
fpioa.set_function(52, FPIOA.GPIO52)
uart = UART(UART.UART2, baudrate=115200, bits=UART.EIGHTBITS, parity=UART.PARITY_NONE, stop=UART.STOPBITS_ONE)
picture_width = 800
picture_height = 480
sensor_id = 2
sensor = None
# 显示模式选择:可以是 "VIRT"、"LCD" 或 "HDMI"
DISPLAY_MODE = "HDMI"
# 根据模式设置显示宽高
if DISPLAY_MODE == "VIRT":
DISPLAY_WIDTH = ALIGN_UP(1920, 16)
DISPLAY_HEIGHT = 1080
elif DISPLAY_MODE == "LCD":
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 480
elif DISPLAY_MODE == "HDMI":
DISPLAY_WIDTH = 1920
DISPLAY_HEIGHT = 1080
else:
raise ValueError("未知的 DISPLAY_MODE,请选择 'VIRT', 'LCD' 或 'HDMI'")
# 定义全局矩阵,表示棋局状态(3x3)
BOARD_SIZE = 3
board_state = [[None for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
last_board_state = [[None for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
def init_board():
"""初始化棋盘状态"""
global board_state
board_state = [[None for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
print("棋盘已初始化")
def update_board(row, col, player):
"""更新棋盘状态
Args:
row (int): 行索引
col (int): 列索引
player (int): 玩家标识(例如,0 表示空格,1 表示黑棋,2 表示白棋)
"""
global board_state
if 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE:
board_state[row][col] = player
print(f"位置 ({row}, {col}) 已更新为 {player}")
else:
print("无效的位置")
def print_board():
"""打印棋盘状态"""
global board_state
for row in board_state:
print(row)
def map_position_to_index(x, y, min_x, max_x, min_y, max_y):
"""将棋子的坐标映射到棋盘的行和列索引
Args:(并非以下)
x (int): 棋子的 x 坐标
y (int): 棋子的 y 坐标
Returns:
tuple: (row, col) 表示棋盘上的行和列索引
"""
grid_width = (max_x - min_x) / 2
grid_height = (max_y - min_y) / 2
col = int((x - min_x) // grid_width)
row = int((y - min_y) // grid_height)
return row, col
def detect_board_and_pieces(img):
"""检测棋盘和棋子
Args:
img: 当前图像
Returns:
tuple: (rects, min_x, max_x, min_y, max_y) 表示九宫格信息和边界坐标
"""
# 在原图上查找九宫格
rects = img.find_blobs(color_rect, invert=False, area_threshold=300)
for rect in rects:
img.draw_rectangle(rect.rect(), colorcolor=(255, 0, 0), thickness=5)
if len(rects) < 9:
print("检测到的九宫格不足9个")
return None, None, None, None, None
min_x = min(rect[0] for rect in rects)
max_x = max(rect[0] for rect in rects)
min_y = min(rect[1] for rect in rects)
max_y = max(rect[1] for rect in rects)
return rects, min_x, max_x, min_y, max_y
# 全局变量,用于存储任务相关的变量
task_vars = {}
try:
sensor = Sensor(id=sensor_id)
sensor.reset()
sensor.set_framesize(width=picture_width, height=picture_height, chn=CAM_CHN_ID_0)
sensor.set_pixformat(Sensor.RGB565, chn=CAM_CHN_ID_0)
clock = utime.clock()
if DISPLAY_MODE == "VIRT":
Display.init(Display.VIRT, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, fps=60)
elif DISPLAY_MODE == "LCD":
Display.init(Display.ST7701, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, to_ide=True)
elif DISPLAY_MODE == "HDMI":
Display.init(Display.LT9611, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, to_ide=True)
MediaManager.init()
sensor.run()
# 设置格子的LAB颜色阈值范围
color_rect = [(45, 70, -3, 34, 8, 56)] # [min_L, max_L, min_A, max_A, min_B, max_B]
# 设置绿灯的LAB颜色阈值范围
color_green = [(98, 100, -5, -2, 0, 8)]
# 设置黑棋子的roi阈值范围
roi_white = (466,101,90,289)
# 设置白棋子的roi阈值范围
roi_black = (152,76,94,299)
# 设置棋盘的boi阈值范围
roi_rect = (227,87,249,289)
# 任务1设置黑棋子二值化阈值范围
binary_black = [(40, 60)]
# 任务1设置白棋子二值化阈值范围
binary_white = [(0, 157)]
# 任务2设置白棋子二值化阈值范围
binary_white_2 = [(0, 157)]
# 任务2设置黑棋子二值化阈值范围
binary_black_2 = [(250, 255)]
color_black = [(0, 32, -24, 36, -29, 17)]
color_white = [(48, 100, -79, 35, -15, 5)]
board_white = [(55, 100, -128, 11, -128, 29)]
board_black = [(0, 31, -128, 11, -128, 29)]
receivemess = None
task_flag = 6
task = 0
message_tect = "abcx\r\n"
uart.write(message_tect)
# 初始化棋盘
init_board()
while True:
os.exitpoint()
clock.tick()
img = sensor.snapshot(chn=CAM_CHN_ID_0)
#global task_vars
if task_flag == 0:
#message_tect = "A\n"
#uart.write(message_tect)
while receivemess == None:
img = sensor.snapshot(chn=CAM_CHN_ID_0)
receivemess = uart.read()
Display.show_image(img, x=DISPLAY_WIDTH - picture_width, y=0, layer=Display.LAYER_OSD1)
time.sleep_ms(1)
# uart.write(receivemess)
if receivemess == b'\x31':
task_flag=1
elif receivemess == b'\x32':
task_flag=2
elif receivemess == b'\x33':
task_flag=3
elif receivemess == b'\x34':
task_flag=4
elif receivemess == b'\x35':
task_flag=5
elif receivemess == b'\x36':
task_flag=6
else :
task_flag=0
print(f"{receivemess}")
receivemess = None
# Display.show_image(img, x=DISPLAY_WIDTH - picture_width, y=0, layer=Display.LAYER_OSD1)
elif task_flag == 1:
#message_tect = "B\n"
#uart.write(message_tect)
# 任务1:初始化棋盘并发送九宫格中心坐标,识别黑棋和白棋的坐标
print("task_flag == 1: 初始化棋盘并发送九宫格中心坐标")
count = 0
# 检测棋盘和棋子
rects = img.find_blobs(color_rect, invert=False, pixels_threshold=2000)
for rect in rects:
img.draw_rectangle(rect.rect(), colorcolor=(255, 0, 0), thickness=5)
print(f"Rect {count}: {rect}")
count += 1
Display.show_image(img, x=0, y=0, layer=Display.LAYER_OSD0)
if len(rects) < 9:
print("检测到的九宫格不足9个")
task_flag = 1
time.sleep(0.5)
continue
sorted_rects_x = sorted(rects, key=lambda x: x[0])
sorted_rects_y = sorted(rects, key=lambda x: x[1])
#print(sorted_rects_y)
#分三组
first_group = [sorted_rects_y[0],sorted_rects_y[1],sorted_rects_y[2]]
second_group = [sorted_rects_y[3],sorted_rects_y[4],sorted_rects_y[5]]
third_group = [sorted_rects_y[6],sorted_rects_y[7],sorted_rects_y[8]]
min_x_first_group = min(sorted_rects_y[0][0],sorted_rects_y[1][0],sorted_rects_y[2][0])
min_x_second_group = min(sorted_rects_y[3][0],sorted_rects_y[4][0],sorted_rects_y[5][0])
min_x_third_group = min(sorted_rects_y[6][0],sorted_rects_y[7][0],sorted_rects_y[8][0])
max_x_first_group = max(sorted_rects_y[0][0],sorted_rects_y[1][0],sorted_rects_y[2][0])
max_x_second_group = max(sorted_rects_y[3][0],sorted_rects_y[4][0],sorted_rects_y[5][0])
max_x_third_group = max(sorted_rects_y[6][0],sorted_rects_y[7][0],sorted_rects_y[8][0])
middle_x = sorted_rects_x[4][0] if len(sorted_rects_x) > 4 else None
middle_y = sorted_rects_y[4][1] if len(sorted_rects_y) > 4 else None
tolerance = 1e-3
middle_rect = None
for rect in rects:
if abs(rect[0] - middle_x) < tolerance and abs(rect[1] - middle_y) < tolerance:
middle_rect = rect
break
if middle_rect is not None:
print(f"中间格: {middle_rect}")
img.draw_rectangle(middle_rect.rect(), color=(0, 255, 0), thickness=5)
# 创建一个字典来存储每个格的坐标
min_x = min(rect[0] for rect in rects)
max_x = max(rect[0] for rect in rects)
min_y = min(rect[1] for rect in rects)
max_y = max(rect[1] for rect in rects)
task_vars = {
"min_x": min_x,
"max_x": max_x,
"min_y": min_y,
"max_y": max_y
}
#print(task_vars)
# 计算每个九宫格的大小
grid_width = (max_x - min_x) / 2
grid_height = (max_y - min_y) / 2
# 确定坐标标号
first_rect = None
second_rect = None
third_rect = None
fourth_rect = None
fifth_rect = None
sixth_rect = None
seventh_rect = None
eighth_rect = None
ninth_rect = None
for rect in first_group:
if abs(rect[0] - min_x_first_group) < tolerance:
first_rect = [rect[5],rect[6]]
if abs(rect[0] - max_x_first_group) < tolerance:
third_rect = [rect[5],rect[6]]
else :
second_rect = [rect[5],rect[6]]
for rect in second_group:
if abs(rect[0] - min_x_second_group) < tolerance:
fourth_rect = [rect[5],rect[6]]
if abs(rect[0] - max_x_second_group) < tolerance:
sixth_rect = [rect[5],rect[6]]
else :
fifth_rect = [rect[5],rect[6]]
for rect in third_group:
if abs(rect[0] - min_x_third_group) < tolerance:
seventh_rect = [rect[5],rect[6]]
if abs(rect[0] - max_x_third_group) < tolerance:
ninth_rect = [rect[5],rect[6]]
else :
eighth_rect = [rect[5],rect[6]]
# 将九宫格的矩形按照1到9的顺序排列
sorted_rects = [
first_rect, # 1
second_rect, # 2
third_rect, # 3
fourth_rect, # 4
fifth_rect, # 5
sixth_rect, # 6
seventh_rect, # 7
eighth_rect, # 8
ninth_rect # 9
]
print(sorted_rects)
# 检查是否有未识别的矩形
for i, rect in enumerate(sorted_rects):
if rect is None:
print(f"未识别到位置 {i+1} 的矩形")
# 使用默认值 (0, 0) 替代 None
sorted_rects[i] = (0, 0)
task_flag = 4
time.sleep(0.5)
# continue
'''
# 发送九宫格中心坐标
rect_coords = {}
for idx, rect in enumerate(sorted_rects):
# 将索引转换为字母(如 0 -> 'a', 1 -> 'b', 2 -> 'c' 等)
key = chr(ord('a') + idx)
# 提取矩形的中心坐标
x = rect[5] # 假设 rect 是一个元组,索引 5 和 6 分别是 x 和 y 坐标
y = rect[6]
# 将中心坐标存储到字典中
rect_coords[key] = (x, y)
# 按字母顺序排序键
sorted_keys = sorted(rect_coords.keys())
'''
# 构建消息字符串
message_rect = '#' + ':'.join([f"{rect[0]}:{rect[1]}" for rect in sorted_rects]) + '#\r\n'
print(f"Sent: {message_rect}", end="")
print("---------RECT_END---------")
print("fps = ", clock.fps())
# 识别黑棋子
#img_gray = img.to_grayscale(copy=True)
# img_gray_black = img.to_grayscale(copy=True).binary(binary_black, invert=False)
blacks = img.find_blobs(color_black, roi=roi_black,pixels_threshold=1000)
count_blacks = 0
black_coords = []
print("------BLACK------")
for black in blacks:
# img.draw_circle(black[5],black[6],20, color=(255, 0, 0), thickness=5)
black_coords.append((int(black[5]), int(black[6])))
print(f"black {count_blacks}: {black}")
count_blacks += 1
#Display.show_image(img, x=DISPLAY_WIDTH - picture_width, y=0, layer=Display.LAYER_OSD1)
if len(blacks) < 5:
task_flag = 1
time.sleep(0.5)
continue
# 按 y 坐标排序黑棋子
black_coords_sorted = sorted(black_coords, key=lambda x: (x[1], x[0]))
# 发送黑棋子坐标
message_black = 'b'+':'.join([f"{x}:{y}" for gid, (x, y) in enumerate(black_coords_sorted)]) + 'b\r\n'
# uart.write(message_black)
print(f"Sent: {message_black}", end="")
# 识别白棋子
#img_gray_white = img.to_grayscale(copy=True).binary(binary_white, invert=False)
whites = img.find_blobs(color_white, roi=roi_white, pixels_threshold=1000)
count_whites = 0
white_coords = []
print("------WHITE------")
for white in whites:
img.draw_circle(white[5],white[6],20, color=(255, 0, 0), thickness=5)
white_coords.append((int(white[5]), int(white[6])))
print(f"white {count_whites}: {white}")
count_whites += 1
Display.show_image(img, x=DISPLAY_WIDTH - picture_width, y=0, layer=Display.LAYER_OSD1)
if len(whites) < 5:
task_flag = 1
time.sleep(0.5)
continue
# 按 y 坐标排序白棋子
white_coords_sorted = sorted(white_coords, key=lambda x: (x[1], x[0]))
# 发送白棋子坐标
message_white = 'w'+':'.join([f"{x}:{y}" for gid, (x, y) in enumerate(white_coords_sorted)]) + 'w\r\n'
uart.write(message_rect)
time.sleep(0.5)
uart.write(message_black)
time.sleep(0.5)
uart.write(message_white)
time.sleep(0.5)
print(f"Sent: {message_white}", end="")
task_flag = 0
receivemess = None
elif task_flag == 2:
#message_tect = "C\n"
#uart.write(message_tect)
# 任务2:识别新的棋盘状态并更新棋盘矩阵,检测棋子位置变化
print("task_flag == 2: 识别新的棋盘状态并更新棋盘矩阵")
min_x = task_vars["min_x"]
max_x = task_vars["max_x"]
min_y = task_vars["min_y"]
max_y = task_vars["max_y"]
#Display.show_image(img, x=0, y=0, layer=Display.LAYER_OSD0)
# 识别黑棋子并更新棋盘状态
blacks = img.find_blobs(board_black, roi=roi_rect,pixels_threshold=1000)
#blacks = img_gray_black.find_circles(roi_rect,threshold=6000)
#Display.show_image(img_gray_black, x=0, y=0, layer=Display.LAYER_OSD0)
print("------BLACK------")
for black in blacks:
row, col = map_position_to_index(black[5], black[6], min_x, max_x, min_y, max_y)
update_board(row, col, 1) # 1 表示黑棋
# 识别白棋子并更新棋盘状态
whites = img.find_blobs(board_white, roi=roi_rect,pixels_threshold=1000)
#whites = img_gray_white.find_circles(roi_rect,threshold=6000)
#Display.show_image(img_gray_white, x=0, y=0, layer=Display.LAYER_OSD0)
print("------WHITE------")
for white in whites:
row, col = map_position_to_index(white[5], white[6], min_x, max_x, min_y, max_y)
update_board(row, col, 2) # 2 表示白棋
# 打印当前棋盘状态
#print("当前棋盘状态:")
#print_board()
'''
# 检测棋子位置变化
changed = False
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE):
if last_board_state[row][col] != board_state[row][col]:
changed = True
print(f"位置 ({row}, {col}) 发生变化: {last_board_state[row][col]} -> {board_state[row][col]}")
if changed:
print("棋盘状态已更新")
else:
print("棋盘状态未发生变化")
'''
# 发送更新后的棋盘状态
board_message = []
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE):
value = board_state[row][col]
# 将 None 转换为 0,表示空格
cell_value = 0 if value is None else value
board_message.append(f"{row*3+col},{cell_value}")
message_board = '@'+':'.join(board_message)+'T\r\n'
uart.write(message_board)
print(f"Sent: {message_board}", end="")
task_flag = 0
receivemess = None
#task_flag = 2 测试用
time.sleep(0.5)
elif task_flag == 3:
#message_tect = "D\n"
#uart.write(message_tect)
greens = img.find_blobs(color_green, invert=True, area_threshold=300)
print("------GREEN------")
if greens:
for green in greens:
img.draw_circle(green[5], green[6],10,color=(0, 0, 255), thickness=3)
print(f"Green Center: X={green[5]}, Y={green[6]}")
green_rel_x = green[5]
green_rel_y = green[6]
message_green = f"L{green_rel_x}:{green_rel_y}L\r\n"
uart.write(message_green)
print(f"Sent: {message_green}", end="")
Display.show_image(img, x=0, y=0, layer=Display.LAYER_OSD0)
#print("---------GREEN_END---------")
#print("fps = ", clock.fps())
receivemess = None
task_flag = 3
elif task_flag == 4:
#message_tect = "E\n"
#uart.write(message_tect)
# 任务4:识别旋转后的棋盘并发送九宫格中心坐标
print("task_flag == 4: 识别旋转后的棋盘并发送九宫格中心坐标")
# 检测棋盘
rects = img.find_blobs(color_rect, invert=False, pixels_threshold=2000)
for rect in rects:
img.draw_rectangle(rect.rect(), colorcolor=(255, 0, 0), thickness=5)
if len(rects) < 9:
print("未检测到九宫格")
task_flag = 4
time.sleep(0.5)
continue
Display.show_image(img, x=0, y=0, layer=Display.LAYER_OSD0)
min_x = min(rect[0] for rect in rects)
max_x = max(rect[0] for rect in rects)
min_y = min(rect[1] for rect in rects)
max_y = max(rect[1] for rect in rects)
sorted_rects_x = sorted(rects, key=lambda x: x[0])
sorted_rects_y = sorted(rects, key=lambda x: x[1])
middle_x = sorted_rects_x[4][0] if len(sorted_rects_x) > 4 else None
middle_y = sorted_rects_y[4][1] if len(sorted_rects_y) > 4 else None
tolerance = 1e-3
# 确定坐标标号
first_rect = None
second_rect = None
third_rect = None
fourth_rect = None
fifth_rect = None
sixth_rect = None
seventh_rect = None
eighth_rect = None
ninth_rect = None
for rect in rects:
if middle_x is not None and middle_y is not None:
if abs(rect[0] - middle_x) < tolerance and abs(rect[1] - middle_y) < tolerance:
fifth_rect = rect
if abs(rect[1] - min_y) < tolerance:
first_rect = rect
if abs(rect[0] - max_x) < tolerance:
third_rect = rect
if abs(rect[0] - min_x) < tolerance:
seventh_rect = rect
if abs(rect[1] - max_y) < tolerance:
ninth_rect = rect
# 收集已识别的点
identified_rects = []
if first_rect is not None:
identified_rects.append(first_rect)
if third_rect is not None:
identified_rects.append(third_rect)
if fifth_rect is not None:
identified_rects.append(fifth_rect)
if seventh_rect is not None:
identified_rects.append(seventh_rect)
if ninth_rect is not None:
identified_rects.append(ninth_rect)
if second_rect is not None:
identified_rects.append(second_rect)
if fourth_rect is not None:
identified_rects.append(fourth_rect)
if sixth_rect is not None:
identified_rects.append(sixth_rect)
if eighth_rect is not None:
identified_rects.append(eighth_rect)
# 将矩形转换为元组以便使用集合运算
def rect_to_tuple(rect):
return (rect[0], rect[1], rect[2], rect[3])
identified_tuples = [rect_to_tuple(rect) for rect in identified_rects]
all_tuples = [rect_to_tuple(rect) for rect in rects]
# 使用集合运算排除已识别的点
identified_set = set(identified_tuples)
all_set = set(all_tuples)
remaining_set = all_set - identified_set
# 将结果转换回列表
remaining_rects = []
for rect in rects:
if rect_to_tuple(rect) in remaining_set:
remaining_rects.append(rect)
#remaining_rects = [rect for rect in sorted_rects if rect not in identified_rects]
#remaining_rects = list(filter(lambda x: x not in identified_rects, sorted_rects))
for rect in remaining_rects:
if first_rect is not None and third_rect is not None:
if first_rect[0] < rect[0] < third_rect[0] and first_rect[1] < rect[1] < third_rect[1]:
second_rect = rect
if first_rect is not None and seventh_rect is not None:
if first_rect[0] > rect[0] > seventh_rect[0] and first_rect[1] < rect[1] < seventh_rect[1]:
fourth_rect = rect
if ninth_rect is not None and third_rect is not None:
if ninth_rect[0] < rect[0] < third_rect[0] and ninth_rect[1] > rect[1] > third_rect[1]:
sixth_rect = rect
if seventh_rect is not None and ninth_rect is not None:
if seventh_rect[0] < rect[0] < ninth_rect[0] and seventh_rect[1] < rect[1] < ninth_rect[1]:
eighth_rect = rect
# 将九宫格的矩形按照1到9的顺序排列
sorted_rects = [
first_rect, # 1
second_rect, # 2
third_rect, # 3
fourth_rect, # 4
fifth_rect, # 5
sixth_rect, # 6
seventh_rect, # 7
eighth_rect, # 8
ninth_rect # 9
]
# 检查是否有未识别的矩形
for i, rect in enumerate(sorted_rects):
if rect is None:
print(f"未识别到位置 {i+1} 的矩形")
# 使用默认值 (0, 0) 替代 None
sorted_rects[i] = (0, 0)
task_flag = 4
time.sleep(0.5)
continue
# 发送九宫格中心坐标
'''
rect_coords = {}
for idx, rect in enumerate(sorted_rects):
# 将索引转换为字母(如 0 -> 'a', 1 -> 'b', 2 -> 'c' 等)
key = chr(ord('a') + idx)
# 提取矩形的中心坐标
x = rect[5] # 假设 rect 是一个元组,索引 5 和 6 分别是 x 和 y 坐标
y = rect[6]
# 将中心坐标存储到字典中
rect_coords[key] = (x, y)
# 按字母顺序排序键
sorted_keys = sorted(rect_coords.keys())
'''
# 构建消息字符串
message_rect = '#' + ':'.join([f"{rect[5]}:{rect[6]}" for rect in sorted_rects]) + '#\r\n'
#rect_coords = {}
#for idx, rect in enumerate(sorted_rects):
# rect_coords[chr(ord('a') + idx)] = (int(rect[5]), int(rect[6]))
#message_rect = '#' + ';'.join([f"{gid},{x},{y}" for gid, (x, y) in enumerate(rect_coords.values())]) + '#\r\n'
uart.write(message_rect)
#print(f"Sent: {message_rect}", end="")
#print("---------RECT_END---------")
#print("fps = ", clock.fps())
#Display.show_image(img, x=0, y=0, layer=Display.LAYER_OSD0)
blacks = img.find_blobs(color_black, roi=roi_black,pixels_threshold=1000)
count_blacks = 0
black_coords = []
print("------BLACK------")
for black in blacks:
img.draw_circle(black[5],black[6],20, color=(255, 0, 0), thickness=5)
black_coords.append((int(black[5]), int(black[6])))
print(f"black {count_blacks}: {black}")
count_blacks += 1
Display.show_image(img, x=DISPLAY_WIDTH - picture_width, y=0, layer=Display.LAYER_OSD1)
if len(blacks) < 5:
task_flag = 1
time.sleep(0.5)
continue
# 按 y 坐标排序黑棋子
black_coords_sorted = sorted(black_coords, key=lambda x: (x[1], x[0]))
# 发送黑棋子坐标
message_black = 'b'+':'.join([f"{x}:{y}" for gid, (x, y) in enumerate(black_coords_sorted)]) + 'b\r\n'
# uart.write(message_black)
print(f"Sent: {message_black}", end="")
# 识别白棋子
#img_gray_white = img.to_grayscale(copy=True).binary(binary_white, invert=False)
whites = img.find_blobs(color_white, roi=roi_white,pixels_threshold=1000)
count_whites = 0
white_coords = []
print("------WHITE------")
for white in whites:
img.draw_circle(white[5],white[6],20, color=(255, 0, 0), thickness=5)
white_coords.append((int(white[5]), int(white[6])))
print(f"white {count_whites}: {white}")
count_whites += 1
if len(whites) < 5:
task_flag = 1
time.sleep(0.5)
continue
# 按 y 坐标排序白棋子
white_coords_sorted = sorted(white_coords, key=lambda x: (x[1], x[0]))
# 发送白棋子坐标
message_white = 'w'+':'.join([f"{x}:{y}" for gid, (x, y) in enumerate(white_coords_sorted)]) + 'w\r\n'
uart.write(message_black)
time.sleep(0.2)
uart.write(message_white)
time.sleep(0.2)
receivemess = None
task_flag = 0
elif task_flag == 5:
button = Pin(52, Pin.OUT, Pin.PULL_NONE)
button.high()
elif task_flag == 6:
button = Pin(52, Pin.OUT, Pin.PULL_NONE)
button.low()
except KeyboardInterrupt as e:
print("用户停止: ", e)
except BaseException as e:
print(f"异常: {e}")
finally:
if isinstance(sensor, Sensor):
sensor.stop()
Display.deinit()
os.exitpoint(os.EXITPOINT_ENABLE_SLEEP)
time.sleep_ms(100)
MediaManager.deinit()
换了一个新的庐山派可以脱机了