python - 将多维数组转换为python中的元组

标签 python arrays stdtuple

我正在以 rgb 值的形式从网络摄像头获取一些帧数据。

import numpy as np    
frame = get_video()
print np.shape(frame)

输出是 (480, 640, 3)。现在我想从这些值构建图像。所以,我想用

im = Image.new("RGB", (480, 640),frame)

但是,这里的第三个参数接受一个元组。我得到这个错误

SystemError: new style getargs format but argument is not a tuple

所以,我的问题是将此帧数据转换为元组的最佳方法是什么,以便我可以构建我的图像。

最佳答案

我在这里假设您正在从 PIL 导入类 Image。

Image.new() 的文档,使用控制台命令 Image.new 访问?是:

在 [3] 中:Image.new?
类型:函数
基类:
字符串形式:
命名空间:Interactive
文件:/usr/lib/python2.7/dist-packages/PIL/Image.py
定义:Image.new(mode, size, color=0)
文档字符串:创建新图像

第三个参数是一个RGB颜色,比如(255,255,255),用来填充空洞图片。您不能使用此函数初始化单个像素。

我还假设 frame 是一个 3D 数组。正如您的输出所示,它是 480 行和 640 行 RGB 元组。

我不知道是否有更简单的方法来做到这一点,但我会通过 putpixel() 函数设置像素值,例如:

im = Image.new( "RGB", (480, 640), (0, 0, 0) ) #initialize 480:640 black image
for i in range(480):
    for j in range(640):
        im.putpixel( (i, j), tuple(frame[i][j]) )

始终通过控制台检查文档字符串,这样可以节省很多时间。我还建议使用 ipython 作为控制台。

关于python - 将多维数组转换为python中的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30950587/

相关文章:

python - 从 Python 脚本中启动守护进程,稍后通过 os.kill 终止它

java - 使用对象调用方法

c++ - 删除在 C++ 中使用 malloc 分配的 std::string 数组

java - 如何按一定顺序打印 3 个不同字符串数组的元素?

c++ - 无法从解压缩的元组初始化 const int

c++ - 错误 : cannot pass objects of non-trivially-copyable type through `...`

python - 布伦特里 + Python : Configure credential at transaction level rather than module

python - 在 python v.3 中打印数字列表

python - 从 GUI 类外部访问 GUI 元素

c++ - 将 std::get 与枚举类一起使用时需要 static_cast