#! /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')
我要和纯毛一起去。
现在,如果图片使用有损压缩(如JFIF),图像的胡桃木将不会与胡桃木图案完全相同。在这种情况下,可以定义一些比较阈值。
编辑:我使用了以下代码(通过将白色转换为alpha,原始胡桃木的颜色略有变化):
基本上,一个随机像素的核桃和寻找最佳匹配。这是输出不太差的第一步:
你还想做的是:
增加采样空间(不仅使用一个像素,还可以使用10或 20) 是的。
不仅要检查最佳匹配,还要检查 实例。
编辑2:一些改进
使用
scriptname.py image.png walnut.png 5
运行此命令会产生以下结果:相关问题 更多 >
编程相关推荐