如何使用python在另一个图像中查找图像

Zac*_*ach 21 python image

我正在尝试使用python来确定一个(小)图像是否在另一个(大)图像中.

在我完全走错路之前的任何建议?

/编辑:好的,一些想法:我正在使用PIL,我正在将每个图像转换为'P'模式,因此我可以将每个像素作为整数进行比较.我正在尝试实现类似Boyer-Moore字符串搜索或Knuth-Morris-Pratt算法的东西,但是在2维中.

也许这会有所帮助:而不是搜索ABC in XXXABCXXX(answer = 4)我们正在寻找

ABC    
DEF    
GHI    
Run Code Online (Sandbox Code Playgroud)

在

XXXXX        
XABCX        
XDEFX       
XGHIX    
XXXXX  
Run Code Online (Sandbox Code Playgroud)

(回答=(2,2))

Zac*_*ach 9

编辑:好的,这是天真的方式:

import Image, numpy

def subimg(img1,img2):
    img1=numpy.asarray(img1)
    img2=numpy.asarray(img2)

    #img1=numpy.array([[1,2,3],[4,5,6],[7,8,9]])
    #img2=numpy.array([[0,0,0,0,0],[0,1,2,3,0],[0,4,5,6,0],[0,7,8,9,0],[0,0,0,0,0]])

    img1y=img1.shape[0]
    img1x=img1.shape[1]

    img2y=img2.shape[0]
    img2x=img2.shape[1]

    stopy=img2y-img1y+1
    stopx=img2x-img1x+1

    for x1 in range(0,stopx):
        for y1 in range(0,stopy):
            x2=x1+img1x
            y2=y1+img1y

            pic=img2[y1:y2,x1:x2]
            test=pic==img1

            if test.all():
                return x1, y1

    return False

small=Image.open('small.tif')
big=Image.open('big.tif')

print subimg(small, big)
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但我想加快速度.我认为关键在于数组'test',我们可以使用它来跳过图像中的某些位置.

编辑2:确保以无损格式使用图像来测试它.

在Mac,安装枕头和from PIL import Image


Tar*_*ula 7

Sikuli使用OpenCV做到这一点,看这里是如何match_by_template工作的,然后使用Python OpenCV绑定来做同样的事情.没有OpenCV这样做应该很难,看看OpenCV文档,搜索模板匹配等...