比赛第一天,我们打算做点提前量
视觉部分任务概述
赛题中,我们应该完成棋盘外棋子的识别,以及棋盘上棋子的识别。对此我们团队的方案为,先利用opencv,对九宫格棋盘进行识别

然后依据识别出九宫格的四个角点,来建立一个屏蔽罩,当识别内部棋子的时候,向外屏蔽,当识别外部棋子的时候,向内屏蔽。
内部棋子的识别
import time
import cv2
import numpy as np
import copy
def main7(image_path):
class BHSBFL:
def __init__(self, image_path):
# 读取图像并转换为灰度图
self.image = cv2.imread(image_path)
self.gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
def find_grid_coordinates(self):
# 应用边缘检测
edges = cv2.Canny(self.gray, 50, 150, apertureSize=3)
# 使用霍夫变换检测直线
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=100, maxLineGap=10)
# 复制原始图像以绘制检测结果(此处不再需要显示)
image_copy = self.image.copy()
# 寻找轮廓
contours_info = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = contours_info[0] if len(contours_info) == 2 else contours_info[1]
if contours:
# 选择最大的轮廓,这通常是九宫格的外框
contour = max(contours, key=cv2.contourArea)
# 获取最小的外接矩形
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
# 计算每个格子的中心并编号
width, height = rect[1]
cell_width = width / 3
cell_height = height / 3
# 确保顶点顺序为左上、右上、右下、左下
box = sorted(box, key=lambda x: (x[1], x[0]))
coordinates = []
for i in range(3):
for j in range(3):
# 计算格子中心
center_x = int(box[0][0] + j * cell_width + cell_width / 2)
center_y = int(box[0][1] + i * cell_height + cell_height / 2)
# 返回编号和中心坐标
coordinates.append((i * 3 + j + 1, (center_x, center_y)))
return coordinates
else:
print("未找到轮廓")
return []
class ChessPieceDetector(BHSBFL):
def __init__(self, image_path):
super().__init__(image_path)
self.image_path = image_path # 存储图像路径
self.coordinates = self.find_grid_coordinates()
self.corner_coordinates = self.find_corners()
self.image = cv2.imread(image_path) # 读取图像
def find_corners(self):
gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(gray, 30, 150)
contours_info = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours_info[0] if len(contours_info) == 2 else contours_info[1]
if contours:
largest_contour = max(contours, key=cv2.contourArea)
rect = cv2.minAreaRect(largest_contour)
box = cv2.boxPoints(rect)
box = np.int0

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



