在图像中找到物体的位置

11

我的目标是使用Python在其他图片中找到特定图像的位置。 以这张图片为例:

enter image description here enter image description here

我想找到图中核桃的位置。已知核桃的图像,因此我认为没有必要进行任何先进的模式匹配或机器学习来判断某个物体是否为核桃。

我该如何找到图像中的核桃位置呢?以下策略是否可行:

  • 使用PIL读取图像
  • 将其转换为Numpy数组
  • 使用Scipy的图像过滤器(哪些过滤器?)

谢谢!

1个回答

15

我会选择使用纯PIL。

  1. 读入图像和核桃。
  2. 选择任意一个核桃的像素。
  3. 找到所有与该颜色相同的图像像素。
  4. 检查周围的像素是否与核桃相同(找到一个不匹配的像素后立即中断以最小化时间)。

现在,如果图片使用有损压缩(如JFIF),则图像中的核桃可能与核桃图案不完全相同。在这种情况下,您可以为比较定义一些阈值。


编辑:我使用了以下代码(通过将白色转换为Alpha,原始核桃的颜色略有变化):

#! /usr/bin/python2.7

from PIL import Image, ImageDraw

im = Image.open ('zGjE6.png')
isize = im.size
walnut = Image.open ('walnut.png')
wsize = walnut.size
x0, y0 = wsize [0] // 2, wsize [1] // 2
pixel = walnut.getpixel ( (x0, y0) ) [:-1]

def diff (a, b):
    return sum ( (a - b) ** 2 for a, b in zip (a, b) )

best = (100000, 0, 0)
for x in range (isize [0] ):
    for y in range (isize [1] ):
        ipixel = im.getpixel ( (x, y) )
        d = diff (ipixel, pixel)
        if d < best [0]: best = (d, x, y)

draw = ImageDraw.Draw (im)
x, y = best [1:]
draw.rectangle ( (x - x0, y - y0, x + x0, y + y0), outline = 'red')
im.save ('out.png')

基本上,选择核桃的一个随机像素并寻找最佳匹配。这是第一步,输出还不错:

enter image description here

你还想要做的是:

  • 增加样本空间(不仅使用一个像素,而是可能使用10或20个)。

  • 不仅检查最佳匹配,而是可能检查最佳的10个匹配。


编辑2:一些改进

#! /usr/bin/python2.7
import random
import sys
from PIL import Image, ImageDraw

im, pattern, samples = sys.argv [1:]
samples = int (samples)

im = Image.open (im)
walnut = Image.open (pattern)
pixels = []
while len (pixels) < samples:
    x = random.randint (0, walnut.size [0] - 1)
    y = random.randint (0, walnut.size [1] - 1)
    pixel = walnut.getpixel ( (x, y) )
    if pixel [-1] > 200:
        pixels.append ( ( (x, y), pixel [:-1] ) )

def diff (a, b):
    return sum ( (a - b) ** 2 for a, b in zip (a, b) )

best = []

for x in range (im.size [0] ):
    for y in range (im.size [1] ):
        d = 0
        for coor, pixel in pixels:
            try:
                ipixel = im.getpixel ( (x + coor [0], y + coor [1] ) )
                d += diff (ipixel, pixel)
            except IndexError:
                d += 256 ** 2 * 3
        best.append ( (d, x, y) )
        best.sort (key = lambda x: x [0] )
        best = best [:3]

draw = ImageDraw.Draw (im)
for best in best:
    x, y = best [1:]
    draw.rectangle ( (x, y, x + walnut.size [0], y + walnut.size [1] ), outline = 'red')
im.save ('out.png')

使用命令 scriptname.py image.png walnut.png 5 运行,例如:

输入图像描述


你能提供带有透明度的核桃单独图像吗?(我想进行一些测试。) - Hyperboreus
在帖子中添加了一个单独的核桃图像,不确定alpha如何与PNG一起使用,但在MS画图中对我有效,使用透明选择工具。 - user2461391
非常感谢!这是我第一次尝试图像处理,所以这对我帮助很大。我注意到只检查一个像素时会出现一些误读,因此我修改了它,检查周围的四个像素并平均差异。现在处理时间更长,但更准确。看来我还有很多要学习的,但感谢您的开端! - user2461391
看看我的第二段代码和结果。相当不错。 - Hyperboreus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接