You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Pillow实现动态图像网格切割及区块坐标与像素统计

基于Pillow的图像动态网格处理方案

需求实现内容

  • 按指定行列数切割图像,先裁剪图像至尺寸可被行列数整除
  • 生成每个网格区块的四角坐标列表(按行从左到右排序)
  • 在原图像上绘制正确的网格线
  • 统计每个网格内的黑色像素数量

完整实现代码

from PIL import Image, ImageDraw

# 配置参数
fileName = 'eyeImg_86.png'
vertical_slices = 8  # 列数(横向切割份数)
horizontal_slices = 4  # 行数(纵向切割份数)

# 1. 读取并裁剪图像
img = Image.open(fileName)
width, height = img.size
# 计算裁剪后的尺寸,确保能被指定行列数整除
new_width = width - (width % vertical_slices)
new_height = height - (height % horizontal_slices)
cropped_img = img.crop((0, 0, new_width, new_height))
# 转为灰度图方便统计黑色像素(黑色像素值为0)
gray_img = cropped_img.convert('L')
pixel_data = gray_img.load()

# 2. 计算网格步长与区块坐标
horizontal_step = new_width // vertical_slices
vertical_step = new_height // horizontal_slices

block_coords = []
# 遍历每个网格区块,按行从左到右收集四角坐标
for row in range(horizontal_slices):
    for col in range(vertical_slices):
        # 计算区块左上角、右上角、右下角、左下角坐标
        x1 = col * horizontal_step
        y1 = row * vertical_step
        x2 = x1 + horizontal_step
        y2 = y1 + vertical_step
        # 四角坐标按左上、右上、右下、左下顺序存储
        block_coords.append([(x1, y1), (x2, y1), (x2, y2), (x1, y2)])

# 3. 绘制网格线
draw_img = cropped_img.convert('RGB')  # 转为RGB模式支持绘制彩色线条
draw = ImageDraw.Draw(draw_img)
line_color = (255, 0, 0)  # 红色网格线,可自定义

# 绘制水平线(横向分割线)
for y in range(0, new_height + 1, vertical_step):
    draw.line([(0, y), (new_width, y)], fill=line_color, width=1)

# 绘制垂直线(纵向分割线)
for x in range(0, new_width + 1, horizontal_step):
    draw.line([(x, 0), (x, new_height)], fill=line_color, width=1)

# 保存带网格的图像
draw_img.save('grid_' + fileName)

# 4. 统计每个区块的黑色像素数量
black_pixel_counts = []
for idx, coords in enumerate(block_coords):
    x1, y1 = coords[0]
    x2, y2 = coords[2]
    count = 0
    for y in range(y1, y2):
        for x in range(x1, x2):
            if pixel_data[x, y] == 0:  # 灰度图中黑色像素值为0
                count += 1
    black_pixel_counts.append(count)
    print(f"区块{idx+1}的黑色像素数量: {count}")

# 输出结果
print("\n所有区块四角坐标列表(按行从左到右):")
for i, coords in enumerate(block_coords):
    print(f"区块{i+1}: {coords}")

关键修正与说明

  1. 网格线绘制修复:原代码错误尝试绘制斜线,改为直接遍历步长生成水平线和垂直线,逻辑简单且无越界问题
  2. 区块坐标生成:直接通过行列索引计算每个区块的四角坐标,无需额外生成网格点矩阵,高效直观
  3. 黑色像素统计:将图像转为灰度图后,通过像素值(0为黑色)判断,遍历区块内像素完成统计
  4. 参数清晰化:明确标注vertical_slices为列数、horizontal_slices为行数,避免混淆

内容的提问来源于stack exchange,提问作者ortunoa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:45:40