python 如何将二进制线扩展到图像的边界?

How to extend binary line to the borders of an image in python?

我想确保像示例中所示的任何二进制线都到达图像的边界。我怎样才能做到这一点?我试过扩张和腐蚀,但如果线的末端和图像的边界之间有很大的差距,它不会解决问题。

以下代码适用于提供的图像。可能不适用于其他人。我正在使用 copy-paste 方法。

from PIL import Image

# Create "patch" image
image = Image.open('image.png')
width, height = image.size
start_position = None
end_position = None
line_width = 0
line_width_count = True
for x in range(width):
    for y in range(height):
        r, g, b = image.getpixel((x, y))
        if all([r, g, b]) and not start_position:
            start_position = x, y

        if line_width_count and all([r, g, b]) and start_position:
            line_width += 1

        if line_width and all([not r, not g, not b]):
            line_width_count = False

        if all([r, g, b]):
            end_position = x, y

patch = Image.open('image.png')
patch = patch.crop((start_position[0], start_position[1], end_position[0], end_position[1]))
patch_width, patch_height = patch.size

# Add top patches
end_pos_x = start_position[0] - patch_width + line_width * 2
end_pos_y = start_position[1] - patch_height + line_width
for i in range(5):
    image.paste(patch, (end_pos_x, end_pos_y))
    end_pos_x -= patch_width - line_width * 2
    end_pos_y -= patch_height - line_width

# Add bottom patches
end_pos_x = end_position[0]-line_width*2
end_pos_y = end_position[1]-line_width
for i in range(5):
    image.paste(patch, (end_pos_x, end_pos_y))
    end_pos_x += patch_width - line_width * 2
    end_pos_y += patch_height - line_width

image.save('result.png')

结果: