如何使用Opencv 3.3和Python2.7识别图像中的迷宫

问题描述 投票:2回答:1

嘿,我正在使用Opencv3.3和Pyhton2.7来识别图像中的迷宫。我必须在图像中找到迷宫的最外层限制。我试着关闭迷宫的入口和出口间隙并找到最外层的形状。我在this工作以缩小差距,但这对我的问题毫无用处,因为我需要这些空白来解决迷宫问题。

这是原始图像

This is the original image

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

这就是我要的

This is what I want

如何提取最外层轮廓?

python-2.7 opencv opencv-contour
1个回答
3
投票

我会用numpy而不是OpenCV来做这个,但是这两个是兼容的,所以你可以混合和匹配,或者你可以在我知道我如何处理它时将技术适应OpenCV。

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

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

enter image description here

我想如果你想谷歌的话,有些人会把这种技术称为“投影”。

所以,代码看起来像这样:

#!/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行,而底部的第8行是第890行。迷宫的左列是第36列,最右边的列是第1509行。

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.