首页 > 解决方案 > 如何生成定制的黑白位图

问题描述

图片示例: 在此处输入图像描述

我想从头开始创建一个黑白位图(不转换或操作现有图像),并且能够使用像素坐标将单个像素更改为黑色或白色,不知何故,也许是通过字典?类似于棋盘的东西,但每个棋盘格有一个像素(如果这有意义吗?)。我找到了一些可以生成色谱图像的东西,但不知道如何调整它。

from PIL import Image

img = Image.new( 'RGB', (300,50), "black") # Create a new black image
pixels = img.load() # Create the pixel map
for i in range(img.size[0]):    # For every pixel:
    for j in range(img.size[1]):
        pixels[i,j] = (i, j, 100) # Set the colour accordingly

img.show()

放大位图的最左边缘

在此处输入图像描述

标签: pythondictionarybitmappython-imaging-librarypixel

解决方案


您可以像这样在这里和那里做单个奇数像素:

from PIL import PIL

# Create new black image - L mode for b/w
img = Image.new( 'L', (10,6))

# Make pixels at locations (0,5) and (2,1) white (255)
img.putpixel((0,5), 255)
img.putpixel((2,1), 255)

# Save result
img.save('result.png')

在此处输入图像描述


但是,如果你想做整行、整列或更长的行,我建议像这样往返于 Numpy:

import numpy as np

# Create new black image - L mode for b/w
img = Image.new( 'L', (10,6))

# Convert to Numpy array for easy processing
na = np.array(img)

# Make row 1 white
na[1,:] = 255

# Make column 8 white
na[:,8] = 255

# Revert to PIL Image from Numpy array and save
Image.fromarray(na).save('result.png')

在此处输入图像描述


或者如果你想做一个块:

... as above ...

na[1:3,5:9] = 255

... as above ...

在此处输入图像描述


推荐阅读