备注
前往结尾 下载完整示例代码。
条形码#
这个演示展示了如何生成条形码。
图表的大小是根据像素宽度计算的,使其为数据点数量的倍数,以防止插值伪影。此外,Axes 被定义为覆盖整个图表,并且所有 Axis 都被关闭。
数据本身通过 imshow 进行渲染。
code.reshape(1, -1)将数据转换为一个包含一行的二维数组。imshow(..., aspect='auto')以允许非方形像素。imshow(..., interpolation='nearest')以防止边缘模糊。无论如何,这不应发生,因为我们已经微调了图像的宽度(以像素为单位),但为了安全起见。
import matplotlib.pyplot as plt
import numpy as np
code = np.array([
1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1,
0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0,
1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1,
1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1])
pixel_per_bar = 4
dpi = 100
fig = plt.figure(figsize=(len(code) * pixel_per_bar / dpi, 2), dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1]) # span the whole figure
ax.set_axis_off()
ax.imshow(code.reshape(1, -1), cmap='binary', aspect='auto',
interpolation='nearest')
plt.show()

参考文献
以下函数、方法、类和模块的使用在本示例中展示: