如何使用Opencv3.3和Pyhton2.7识别图像中的迷宫

时间:2018-08-29 15:12:02

标签: python-2.7 opencv opencv-contour

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

这是原始图片

This is the original image

我想找到迷宫的最外层极限。

这就是我想要的

This is what I want

如何提取最外轮廓?

1 个答案:

答案 0 :(得分:3)

我会使用numpy而不是OpenCV来做到这一点,但是两者是兼容的,因此您可以随意混合和匹配,或者一旦您了解我的解决方法后就可以将其应用于OpenCV。

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

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

enter image description here

如果您想使用Google,我认为有些人将其称为“投影”

因此,代码如下所示:

#!/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列,最右列是col 1509。

如果我在80%的透明红色矩形上绘制以匹配这些位置,则会得到:

enter image description here

相关问题