python - 查找图像中对象的位置

标签 python image-processing python-imaging-library

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

enter image description here enter image description here

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

我将如何找到图像中的核桃?按照这些思路制定的策略是否可行:

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

谢谢!

最佳答案

我会选择纯 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 运行它会产生例如:

enter image description here

关于python - 查找图像中对象的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21338431/

相关文章:

python - 基于边缘像素图的图像分割

Python从csv文件中提取唯一记录

像 C++ 中一样的 python 3d 数组

python - 使用 RegEx 从 Python 字符串的开头去除所有非字母字符

java - 允许数组中的线程不安全

php - 存储上传的图像而不会耗尽空间

Python3 tkinter 设置图像大小

Django - 获取 PIL 图像保存方法以与 Amazon s3boto 存储一起使用

python - 如何在 Python 中打开图像

python - 计算方法无法分配product.template。奥杜 14