Separate/reposition/translate 图像中的形状和 python 中的枕头

Separate/reposition/translate shapes in image with pillow in python

我需要用 python 分离、平移或替换图像中的像素,以便所有形状彼此共享相同的距离和 canvas 的限制。

背景为白色,形状为黑色。

重要提示:图像是动态的,所有图像在不同位置都有条,这意味着我需要检测条开始的位置和条结束的位置以绘制最终图像!

这是一个示例输入图像

这是一个示例输出图像

我是手工做的,我不知道所有的条形图之间的距离是否相同,这只是一个例子。

生成的 canvas 大小也可以更改,但理想情况下我希望所有 canvas 在重新定位条后具有相同的宽度和高度。

图像中的所有像素都是黑色或白色,这样应该会容易得多。

到目前为止我已经尝试过检测形状,但是当某些形状彼此太靠近时无法正确检测到它们:

saut = 1
start_ab = 0
end_ab = 0
start_or = im2.size[1] - 1
end_or = 0
size = 0

shapes = []

for y in range(0, im2.size[0], saut):  # slice across
    for x in range(0, im2.size[1], 1):  # slice down
        pix = im2.getpixel((y, x))
        if pix != 255:
            start_or = min(start_or, x)
            end_or = max(end_or, x)
            inshape = True

    if foundshape == False and inshape == True:
        foundshape = True
        start_ab = y

    if foundshape == True and inshape == False:
        foundshape = False
        end_ab = y
        size = max(size, end_ab)
        shapes.append((start_ab, end_ab, start_or, end_or))
        start_or = im2.size[1] - 1
        end_or = 0
    inshape = False

print shapes
# example shapes output NOT FROM THE EXAMPLE IMAGES PROVIDED but from other shapes [(54, 171, 72, 233), (216, 324, 108, 251), (342, 486, 0, 215), (513, 765, 18, 260), (792, 918, 90, 242)]

而且还得画新图,我不知道怎么画,还有一些图里面有 "holes" 的形状,所以 "redraw" 有点比较复杂。

And still have to draw the new image, i don't know how to do that, also some images have shapes with "holes" in them, so that makes the "redraw" a little bit more complicated.

一旦确定了矩形的边界,就可以使用 Image.crop() 函数从图像中提取矩形(包括那些孔)并使用 Image.paste() 粘贴他们在正确的位置。该教程包含一个示例:

http://pillow.readthedocs.org/en/latest/handbook/tutorial.html#cutting-pasting-and-merging-images

计算每个形状之间距离的代码。它假定形状具有相同的宽度:

def calcDistanceBetweenShapes(nShapes, shapeWidth, totalWidth):
    totalBlank = totalWidth-nShapes*shapeWidth
    return totalBlank/nShapes

移动形状横坐标的代码(假设形状存储为 (start_ab, end_ab, start_or, end_or,empty_points)):

def setNewAbscissa(shape, new_start_ab):
    start_ab, end_ab = shape[0], shape[1]
    shift = new_start_ab - start_ab
    new_end_ab = end_ab + shift
    new_empty_points = map(lambda pt: (pt[0]+shift,pt[1]),empty_points)
    return (new_start_ab, new_end_ab,start_or, end_or, new_empty_points)

现在我们称d形状之间的距离。第一个形状不会移动,所以它的坐标保持不变。第二个形状的 start_ab 将是 previous_end_ab+d 其中 previous_end_ab 是第一个形状的 end_ab 等。这给出了一个算法来计算所有的坐标形状。

def get_new_shapes(shapes, totalWidth):
    shift = calcDistanceBetweenShapes(len(shapes), shapes[0][1] - shape[0][0], totalWidth)
    res = [shapes[0]]
    previous_shape = shapes[0]
    for shape in shape[1:]:
         new_start_ab = previous_shape[1] + shift
         new_shape =  setNewAbscissa(previous_shape,new_start_ab)
         res.append(new_shape)
         previous_shape = new_shape