import png
import numpy as np
# The following import is just for creating an interesting array
# of data. It is not necessary for writing a PNG file with PyPNG.
from scipy.ndimage import gaussian_filter
# Make an image in a numpy array for this demonstration.
nrows = 240
ncols = 320
np.random.seed(12345)
x = np.random.randn(nrows, ncols, 3)
# y is our floating point demonstration data.
y = gaussian_filter(x, (16, 16, 0))
# Convert y to 16 bit unsigned integers.
z = (65535*((y - y.min())/y.ptp())).astype(np.uint16)
# Use pypng to write z as a color PNG.
with open('foo_color.png', 'wb') as f:
writer = png.Writer(width=z.shape[1], height=z.shape[0], bitdepth=16,
greyscale=False)
# Convert z to the Python list of lists expected by
# the png writer.
z2list = z.reshape(-1, z.shape[1]*z.shape[2]).tolist()
writer.write(f, z2list)
# Here's a grayscale example.
zgray = z[:, :, 0]
# Use pypng to write zgray as a grayscale PNG.
with open('foo_gray.png', 'wb') as f:
writer = png.Writer(width=z.shape[1], height=z.shape[0], bitdepth=16,
greyscale=True)
zgray2list = zgray.tolist()
writer.write(f, zgray2list)
import numpy as np
import numpngw
# The following import is just for creating an interesting array
# of data. It is not necessary for writing a PNG file.
from scipy.ndimage import gaussian_filter
# Make an image in a numpy array for this demonstration.
nrows = 240
ncols = 320
np.random.seed(12345)
x = np.random.randn(nrows, ncols, 3)
# y is our floating point demonstration data.
y = gaussian_filter(x, (16, 16, 0))
# Convert y to 16 bit unsigned integers.
z = (65535*((y - y.min())/y.ptp())).astype(np.uint16)
# Use numpngw to write z as a color PNG.
numpngw.write_png('foo_color.png', z)
# Here's a grayscale example.
zgray = z[:, :, 0]
# Use numpngw to write zgray as a grayscale PNG.
numpngw.write_png('foo_gray.png', zgray)
5条答案
按热度按时间xn1cxnb41#
一种替代方法是使用pypng。您仍然需要安装另一个包,但它是纯Python,所以这应该很容易。(实际上在pypng源代码中有一个Cython文件,但它的使用是可选的。)
下面是一个使用pypng将NumPy数组写入PNG的示例:
以下是颜色输出:
下面是灰度输出:
numpngw
的库(在PyPI
和github
上可用),它提供了将NumPy数组写入PNG文件的函数。该存储库有一个setup.py
文件,用于将其作为包安装,但基本代码位于一个文件numpngw.py
中,该文件可以复制到任何方便的位置。numpngw
的唯一依赖项是NumPy。下面是一个脚本,它生成与上面所示相同的16位图像:
nue99wik2#
这个关于PNG和Numpngw的解释非常有帮助!但是,有一个小“错误”我想我应该提一提。在转换为16位无符号整数时,y.max()应该是y.min()。对于随机颜色的图片,这并不重要,但对于真实的图片,我们需要正确地处理它。以下是更正后的代码行。
p1iqtdky3#
您可以将16位数组转换为双通道图像(甚至可以将24位数组转换为3通道图像)。像这样的东西运行得很好,只需要NumPy:
结果:
ccgok5k54#
如前所述,PyPNG非常有用。对于EnThink用户,可以将其安装为:
我会使用货架的
from_array
方法:模式使用PIL样式格式,例如“L”、“LA”、“RGB”或“RGBA”,后跟“;16”或“;8”太设置位深度。如果省略位深度,则使用数组的数据类型。
阅读更多here。
bqf10yzr5#
创建了一个仅使用NumPy和OpenCV即可完成此任务的定制脚本:(尽管感觉仍有些过头了……)