在imag中查找对象的位置

2024-06-26 14:12:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是使用python在其他图像上找到特定图像的位置。举个例子:

enter image description hereenter image description here

我想在图像中找到核桃的位置。核桃的图像是已知的,所以我认为不需要任何先进的模式匹配或机器学习来判断某个东西是否是核桃。

我怎样才能找到图像中的核桃呢?这样的策略行得通吗

  • 使用PIL读取图像
  • 将它们转换为Numpy数组
  • 使用Scipy的图像过滤器(什么过滤器?)

谢谢!


Tags: 图像numpy机器过滤器目标pilscipy数组
1条回答
网友
1楼 · 发布于 2024-06-26 14:12:26

我要和纯毛一起去。

  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) 是的。

  • 不仅要检查最佳匹配,还要检查 实例。


编辑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运行此命令会产生以下结果:

enter image description here

相关问题 更多 >