栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

PySide: Separating a spritesheet / Separating an image into contiguous regionsof color

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PySide: Separating a spritesheet / Separating an image into contiguous regionsof color

That sounds like something that should be implemented in anything that deals
with sprites, but here we will implement our own sprite-spliter.

The first thing we need here is to extract the individual objects. In this
situation, it is only a matter of deciding whether a pixel is a background one
or not. If we assume the point at origin is a background pixel, then we are
done:

from PIL import Imagedef sprite_mask(img, bg_point=(0, 0)):    width, height = img.size    im = img.load()    bg = im[bg_point]    mask_img = Image.new('L', img.size)    mask = mask_img.load()    for x in xrange(width):        for y in xrange(height): if im[x, y] != bg:     mask[x, y] = 255    return mask_img, bg

If you save the

mask
image created above and open it, here is what you would
see on it (I added a rectangle inside your empty window):

With the image above, the next thing we need is to fill its holes if we want
to join sprites that are inside others (like the rectangle added, see figure
above). This is another simple rule: if a point cannot be reached from the
point at [0, 0], then it is a hole and it must be filled. All that is left is
then separating each sprite in individual images. This is done by connected
component labeling. For each component we get its axis-aligned bounding box in
order to define the dimensions of the piece, and then we copy from the
original image the points that belong to a given component. To keep it short,
the following pre uses

scipy
for these tasks:

import sysimport numpyfrom scipy.ndimage import label, morphologydef split_sprite(img, mask, bg, join_interior=True, basename='sprite_%d.png'):    im = img.load()    m = numpy.array(mask, dtype=numpy.uint8)    if join_interior:        m = morphology.binary_fill_holes(m)    lbl, ncc = label(m, numpy.ones((3, 3)))    for i in xrange(1, ncc + 1):        px, py = numpy.nonzero(lbl == i)        xmin, xmax, ymin, ymax = px.min(), px.max(), py.min(), py.max()        sprite = Image.new(img.mode, (ymax - ymin + 1, xmax - xmin + 1), bg)        sp = sprite.load()        for x, y in zip(px, py): x, y = int(x), int(y) sp[y - int(ymin), x - int(xmin)] = im[y, x]        name = basename % i        sprite.save(name)        print "Wrote %s" % namesprite = Image.open(sys.argv[1])mask, bg = sprite_mask(sprite)split_sprite(sprite, mask, bg)

Now you have all the pieces (sprite_1.png, sprite_2.png, …, sprite_8.png)
exactly as you included in the question.



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/634157.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号