如何使用python在另一个图像中查找图像 [英] How to find an image within another image using python

查看:3806
本文介绍了如何使用python在另一个图像中查找图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use python to determine if one (small) image is within another (large) image.

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

Any suggestions before I take myself completely down the wrong path?

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

/edit: Ok, some ideas: I'm using PIL, and I'm converting each image to the 'P' mode so I can compare each pixel as an integer. I'm trying to implement something like a Boyer–Moore string search or the Knuth–Morris–Pratt algorithm, but in 2 dimensions.

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

Maybe this will help: instead of searching for ABC in XXXABCXXX (answer=4) we are searching for

ABC    
DEF    
GHI    

in

XXXXX        
XABCX        
XDEFX       
XGHIX    
XXXXX  

(答案=(2,2))

推荐答案

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

Ok, here is the naive way to do this:

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)

它工作正常,但我想加速它向上。我认为关键在于数组'test',我们可以使用它来跳过图像中的某些位置。

It works just fine, but I want to SPEED IT UP. I think the key is in the array 'test' which we might be able to use to skip some positions in the image.

编辑2:确保使用图像用于测试此功能的无损格式。

Edit 2: Make sure you use images in a loss-less format to test this.

Mac 上,安装Pillow和 PIL导入图像

On Mac, install Pillow and from PIL import Image

这篇关于如何使用python在另一个图像中查找图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆