检测棋盘 OpenCV 中的方块

Yas*_*n12 2 python opencv image image-processing computer-vision

我在 python 中使用 OpenCV 检测到了一个棋盘:

  • 计算图像的边缘
  • 计算霍夫变换
  • 寻找霍夫变换的局部最大值
  • 提取图像线条

然后我使用了findContoursanddrawContours函数:

  im_gray = cv2.imread('redLines.png', cv2.IMREAD_GRAYSCALE)
  kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))  
  morphed = cv2.dilate(im_gray, kernel, iterations=1)
  (ret, thresh) = cv2.threshold(morphed, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
  contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  cv2.drawContours(thresh, contours, -1, (255, 255, 255), 3)
Run Code Online (Sandbox Code Playgroud)

效果很好,最后的 imshow 看起来像这样:

在此输入图像描述

现在,我尝试检测网格中的每个方块并将其点保存在向量中的唯一索引中。

我知道我可以使用轮廓数组来做到这一点。但是当我打印轮廓的长度时,它不断快速变化,从尺寸 2 到 112。

所以我猜它不能很好地识别网格。

任何帮助,将不胜感激。

nat*_*ncy 6

一种方法是采用轮廓区域过滤+形状近似。由于正方形有 4 个角,因此如果轮廓有四个顶点,我们可以假设它是正方形。

检测到的绿色方块

在此输入图像描述

孤立的方块

在此输入图像描述

import cv2
import numpy as np

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.png")
mask = np.zeros(image.shape, dtype=np.uint8)
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Remove noise with morph operations
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
invert = 255 - opening

# Find contours and find squares with contour area filtering + shape approximation
cnts = cv2.findContours(invert, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    if len(approx) == 4 and area > 100 and area < 10000:
        x,y,w,h = cv2.boundingRect(c)
        cv2.drawContours(original, [c], -1, (36,255,12), 2)
        cv2.drawContours(mask, [c], -1, (255,255,255), -1)

cv2.imshow("original", original)
cv2.imshow("mask", mask)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)