我的目标是使用python在其他图像上找到特定图像的位置。举个例子:
我想在图像中找到核桃的位置。核桃的形象是众所周知的,所以我认为不需要任何先进的模式匹配或机器学习来判断核桃是否是核桃。
如何在图像中找到核桃?这些方面的战略是否有效:
谢谢!
答案 0 :(得分:10)
我会选择纯PIL。
现在,如果图片使用有损压缩(如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')
基本上,核桃的一个随机像素,寻找最佳匹配。这是输出不太糟糕的第一步:
你还想做的是:
增加样本空间(不仅使用一个像素,而且可能是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
运行此操作会产生例如: