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

  • 计算图像的边缘
  • 计算Hough变换
  • 寻找Hough变换的局部极大值
  • 提取图像线

然后我使用了findContoursdrawContours个函数:

  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)

而且效果很好,最后一场imshow看起来是这样的:

enter image description here

现在,我试图检测网格中的每个正方形,并将其点保存在向量中唯一的索引中.

我知道我可以用轮廓数组来做.但是,当我打印轮廓的长度时,它一直在快速变化,从2号到112号..

所以我猜它没有很好地识别网格.

任何帮助都将不胜感激.

推荐答案

一种方法是使用contour area filtering+shape approximation.因为一个正方形有四个角,如果一个轮廓有四个顶点,我们可以假设它是一个正方形.

检测到绿色方块

enter image description here

孤立的正方形

enter image description here

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()

Python相关问答推荐

使用Python OpenCV的文本检测分割

Python中两个矩阵的自定义Hadamard风格产物

指示组内的rejected_time是否在creation_timestamp后5分钟内

Python -Polars库中的滚动索引?

如何才能知道Python中2列表中的巧合.顺序很重要,但当1个失败时,其余的不应该失败或是0巧合

如何使用Jinja语法在HTML中重定向期间传递变量?

替换字符串中的多个重叠子字符串

DataFrame groupby函数从列返回数组而不是值

在Python中处理大量CSV文件中的数据

大小为M的第N位_计数(或人口计数)的公式

如何获取numpy数组的特定索引值?

ODE集成中如何终止solve_ivp的无限运行

在含噪声的3D点网格中识别4连通点模式

Pandas GroupBy可以分成两个盒子吗?

CommandeError:模块numba没有属性generated_jit''''

如何在TensorFlow中分类多个类

Geopandas未返回正确的缓冲区(单位:米)

numpy.unique如何消除重复列?

为用户输入的整数查找根/幂整数对的Python练习

Python Mercury离线安装