如何在Python中生成可自定义像素宽高与颜色的图像?
在Python中用数组自定义生成图像的方法
下面介绍两种常用的实现方式,都基于NumPy数组来精准控制每个像素的颜色:
方法一:使用Pillow + NumPy
Pillow是Python生态中最常用的图像处理库,配合NumPy可以轻松实现像素级的自定义操作。
步骤&代码示例
- 先安装依赖:
pip install pillow numpy
- 编写代码生成图像:
import numpy as np from PIL import Image # 定义图像的宽度和高度 width, height = 200, 100 # 创建RGB格式的数组,形状为(高度, 宽度, 3),数据类型为uint8(对应0-255的颜色值) image_array = np.zeros((height, width, 3), dtype=np.uint8) # 自定义像素颜色:直接通过数组索引赋值 # 左上角100x50区域设为红色(RGB:255,0,0) image_array[:50, :100] = [255, 0, 0] # 右下角100x50区域设为蓝色(RGB:0,0,255) image_array[50:, 100:] = [0, 0, 255] # 中间区域设为绿色(RGB:0,255,0) image_array[25:75, 50:150] = [0, 255, 0] # 将NumPy数组转换为Pillow图像对象 img = Image.fromarray(image_array) # 保存图像到本地 img.save("custom_rgb_image.png") # 直接显示图像 img.show()
方法二:使用OpenCV + NumPy
OpenCV适合需要后续做计算机视觉处理的场景,注意它的颜色通道顺序是BGR(和Pillow的RGB相反)。
步骤&代码示例
- 安装依赖:
pip install opencv-python numpy
- 编写代码:
import numpy as np import cv2 width, height = 200, 100 # 创建BGR格式的数组,形状同样是(高度, 宽度, 3) image_array = np.zeros((height, width, 3), dtype=np.uint8) # OpenCV用BGR顺序赋值,红色对应(0,0,255) image_array[:50, :100] = [0, 0, 255] # 左上角红色 image_array[50:, 100:] = [255, 0, 0] # 右下角蓝色 image_array[25:75, 50:150] = [0, 255, 0] # 中间绿色 # 保存图像 cv2.imwrite("custom_cv_image.png", image_array) # 显示图像(需要按任意键关闭窗口) cv2.imshow("Custom Image", image_array) cv2.waitKey(0) cv2.destroyAllWindows()
额外说明
- 数组的形状必须是**(高度, 宽度, 3)(彩色图)或(高度, 宽度)**(灰度图),因为NumPy按行优先存储,行对应图像的高度维度
- 颜色值必须是0-255之间的整数,所以数组要指定
dtype=np.uint8(无符号8位整数) - 灰度图示例:
import numpy as np from PIL import Image width, height = 200, 100 # 创建灰度图数组,形状为(高度, 宽度) gray_array = np.zeros((height, width), dtype=np.uint8) # 生成从左到右的灰度渐变(0到255) gray_array[:, :] = np.linspace(0, 255, width, dtype=np.uint8) gray_img = Image.fromarray(gray_array) gray_img.save("gradient_gray_image.png") gray_img.show()
内容的提问来源于stack exchange,提问作者Patientes
相关产品推荐
相关产品推荐

