如何生成定制的黑白位图

How to generate a bespoke black and white bitmap

图片示例:

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

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()

在位图的最左边放大

你可以像这样到处做单个奇数像素:

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 ...