黑色区域原地扩张

python设计一个扩张方式,以一张黑白png图片中的4*4黑色方块中心对黑色部分扩张为8*8得到黑色方块

  1. 使用Pillow库中的Image模块来读取PNG图片,并将其转化为灰度图像,也就是每个像素点只有一个值(0-255),代表黑白程度。
  2. 遍历图片的每个像素,找到所有黑色方块的位置和大小。
  3. 对于每个黑色方块,计算它的中心点位置,并构造一个8*8的正方形,在中心点处绘制黑色方块。
  4. 将生成的新图像保存为PNG格式。
from PIL import Image, ImageDraw

# 读取PNG图片并转化为灰度图像
im = Image.open("E:/临时文件/image_with_square.png").convert('L')

# 获取图像尺寸
width, height = im.size

# 创建一个空白图像,并将其填充为白色
new_im = Image.new('L', (width, height), 'white')

# 创建一个画笔对象,用于绘制新图像
draw = ImageDraw.Draw(new_im)

# 遍历每个像素,找到所有黑色方块的位置和大小
for x in range(width):
    for y in range(height):
        # 如果当前像素是黑色,就找到其所在的黑色方块
        if im.getpixel((x, y)) == 0:
            left, top, right, bottom = x, y, x, y
            while left > 0 and im.getpixel((left - 1, y)) == 0:
                left -= 1
            while right < width - 1 and im.getpixel((right + 1, y)) == 0:
                right += 1
            while top > 0 and im.getpixel((x, top - 1)) == 0:
                top -= 1
            while bottom < height - 1 and im.getpixel((x, bottom + 1)) == 0:
                bottom += 1

            # 计算黑色方块的中心点位置
            cx = (left + right) // 2
            cy = (top + bottom) // 2

            # 在中心点位置构造8*8的正方形,并绘制黑色方块
            draw.rectangle([(cx - 3, cy - 3), (cx + 4, cy + 4)], fill='black')

# 将生成的新图像保存为PNG格式
new_im.save("E:/临时文件/qq2.png")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值