首页 > 解决方案 > 如何使用 Opencv3.3 和 Pyhton2.7 识别图像中的迷宫

问题描述

嘿,我正在使用 Opencv3.3 和 Pyhton2.7 来识别图像中的迷宫。我必须在图像中找到迷宫的最外边界。我尝试关闭迷宫的入口和出口间隙并找到最外面的形状。我致力于缩小差距,但这 对我的问题没有用,因为我需要这些差距来解决迷宫。

这是原图

这是原图

我想找到迷宫的最外面的界限。

这就是我要的

这就是我要的

如何提取最外面的轮廓?

标签: python-2.7opencvopencv-contour

解决方案


我会使用numpyOpenCV 而不是 OpenCV,但两者是兼容的,所以无论如何你都可以混合搭配,或者一旦你知道我是如何处理它的,你就可以将该技术适应 OpenCV。

该策略是将每一行的所有像素相加,并制作一个单像素宽的图像(如下右图所示),它是每行中所有像素的总和。然后我在该列中找到最大值并除以将所有内容标准化为 0..100 范围。现在,该单像素宽图像中小于 30 的任何像素都意味着相应行在原始图像中的白色像素少于 30% - 即它大部分是黑色的。

然后我对所有列进行相同的求和以产生列总和 - 显示在下图的底部:

在此处输入图像描述

如果你想用谷歌搜索它,我认为有些人将这种技术称为“投影” 。

因此,代码如下所示:

#!/usr/local/bin/python3

import numpy as np
from PIL import Image

# Load image - you can use OpenCV "imread()" just the same and convert to grayscale
im = np.array(Image.open('maze.jpg').convert('L'))

# Get height and width
h,w = im.shape[0:2]

# Make a single pixel wide column, same height as image to store row sums in
rowsums=np.empty((h))      
# Sum all pixels in each row
np.sum(im,axis=1,out=rowsums)        
# Normalize to range 0..100, if rowsum[i] < 30 that means fewer than 30% of the pixels in row i are white
rowsums /= np.max(rowsums)/100      

# Find first and last row that is largely black
first = last = -1
for r in range(h):
    if first < 0 and rowsums[r] < 30:
        first = r
    if rowsums[r] < 30:
        last = r

print(first,last)

# Make a single pixel tall row, same width as image to store col sums in
colsums=np.empty((w))      
# Sum all pixels in each col
np.sum(im,axis=0,out=colsums)        
# Normalize to range 0..100, if colsum[i] < 30 that means fewer than 30% of the pixels in col i are white
colsums /= np.max(colsums)/100      

# Find first and last col that is largely black
first = last = -1
for c in range(w):
    if first < 0 and colsums[c] < 30:
        first = c
    if colsums[c] < 30:
        last = c

print(first,last)

输出:

62 890
36 1509

所以迷宫的顶行是第 62 行,底行是第 890 行。迷宫的左列是第 36 列,最右列是第 1509 列。

如果我绘制一个 80% 透明的红色矩形来匹配这些位置,我会得到:

在此处输入图像描述


推荐阅读