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

如何使用Python或Matlab生成像素值对应高度的JPG图像

实现方案

以下分别提供Python和Matlab两种可直接运行的实现代码:

Python 实现

依赖第三方库numpy和Pillow,先执行安装命令:

pip install numpy pillow

运行代码:

import numpy as np
from PIL import Image

# 定义图像尺寸:高343,宽389
h, w = 343, 389

# 生成1~343的行数值序列,扩展为每行所有列数值一致的数组
# 使用uint16类型适配超出8位最大值255的数值范围
row_values = np.arange(1, h+1, dtype=np.uint16).reshape(h, 1)
gray_img = np.repeat(row_values, w, axis=1)

# 导出为JPG文件
img = Image.fromarray(gray_img, mode="I;16")
img.save("row_gradient.jpg")

注意:常规8位JPG单通道像素最大值为255,如果你需要兼容普通8位格式,可添加线性映射将数值压缩到0~255范围,对应修改生成数组的代码为gray_img = np.repeat((row_values * 255 / h).astype(np.uint8), w, axis=1)即可,导出时修改mode为L。

Matlab 实现

直接运行以下代码即可:

% 定义图像尺寸
h = 343;
w = 389;

% 生成每行值统一的灰度数组,转16位类型适配数值范围
gray_img = repmat(uint16(1:h)', 1, w);

% 导出为无损JPG避免数值损失
imwrite(gray_img, "row_gradient.jpg", "Mode", "lossless")

若需导出8位JPG,将数组生成代码修改为gray_img = repmat(uint8((1:h)*255/h)', 1, w)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 12:15:01