【问题标题】:How to extend binary line to the borders of an image in python?如何在python中将二进制线扩展到图像的边界?
【发布时间】:2021-12-22 02:28:27
【问题描述】:

我想确保任何像示例中所示的二进制线都到达图像的边界。我怎样才能做到这一点?我尝试过扩张和侵蚀,但如果行尾和图像边框之间存在很大差距,则无法解决问题。

【问题讨论】:

  • 你能分享预期的图像吗?
  • 我已经包含了一个具有预期结果的示例。谢谢!

标签: python mask image-segmentation


【解决方案1】:

以下代码适用于提供的图像。可能不适用于其他人。我正在使用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')

结果:

【讨论】:

  • 谢谢!你的解决方案解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 2013-05-20
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
相关资源
最近更新 更多