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

如何用Python修改图像X轴、Y轴上每隔n个像素的颜色?

Python批量修改图像隔n像素的颜色方案

用Pillow库可以高效完成这个需求,彻底避免手动逐个像素修改的低效问题。以下是两种实现方案:

基础实现(Pillow原生方法)

from PIL import Image

# 打开目标图像
img = Image.open("your_image.png")
# 转换为可编辑的RGB模式(图像带透明通道则用RGBA)
img = img.convert("RGB")
width, height = img.size

# 自定义参数:间隔像素数n、目标颜色(RGB格式)
n = 10
target_color = (255, 0, 0)  # 示例为纯红色

# 修改X轴方向每隔n行的所有像素
for y in range(0, height, n):
    for x in range(width):
        img.putpixel((x, y), target_color)

# 修改Y轴方向每隔n列的所有像素
for x in range(0, width, n):
    for y in range(height):
        img.putpixel((x, y), target_color)

# 保存处理后的图像
img.save("modified_image.png")

高效优化方案(结合Numpy)

针对大尺寸图像,用Numpy数组操作能大幅提升速度:

from PIL import Image
import numpy as np

img = Image.open("your_image.png")
# 将图像转为Numpy数组,方便批量操作
img_array = np.array(img)

n = 10
# 目标颜色,带透明通道则改为[255, 0, 0, 255]
target_color = [255, 0, 0]

# 批量修改每隔n行的所有像素
img_array[::n, :] = target_color
# 批量修改每隔n列的所有像素
img_array[:, ::n] = target_color

# 转回图像格式并保存
modified_img = Image.fromarray(img_array)
modified_img.save("modified_image.png")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:42:50