python设计一个扩张方式,以一张黑白png图片中的4*4黑色方块中心对黑色部分扩张为8*8得到黑色方块
- 使用Pillow库中的Image模块来读取PNG图片,并将其转化为灰度图像,也就是每个像素点只有一个值(0-255),代表黑白程度。
- 遍历图片的每个像素,找到所有黑色方块的位置和大小。
- 对于每个黑色方块,计算它的中心点位置,并构造一个8*8的正方形,在中心点处绘制黑色方块。
- 将生成的新图像保存为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")