【问题标题】:Converting multi-dimensional array to a tuple in python在python中将多维数组转换为元组
【发布时间】:2015-06-20 05:24:06
【问题描述】:

我从网络摄像头以 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

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

【问题讨论】:

  • get_video() 有什么作用?
  • get_video() 获取视频帧的 RGB 值。所以基本上帧包含 480x640 RGB 值。

标签: python arrays stdtuple


【解决方案1】:

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

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

在 [3] 中:Image.new?
类型:函数
基类:
字符串形式:
命名空间:交互式
文件:/usr/lib/python2.7/dist-packages/PIL/Image.py
定义:Image.new(模式、大小、颜色=0)
文档字符串:创建新图像

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

我还假设框架是一个 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 作为您的控制台。

【讨论】:

  • 非常感谢。如果您将im.putpixel( (i, j), frame[i][j] ) 替换为im.putpixel( (i, j), tuple(frame[i][j]) ),我将接受您的回答。它工作得很好,但我实际上正在尝试直播这个视频,它工作得非常慢。有没有更好的方法来做到这一点?
  • 完成。这可能是一个更好的方法,我从未真正使用过 PIL。
【解决方案2】:

我发现这个实现更快

from PIL import Image

im = Image.new("RGB", (480, 640), (0, 0, 0) ) #initialize 480:640 black image
while True:
 frame = get_video()
 im = Image.fromarray(frame)
 im.save('some-name', 'JPEG')

【讨论】:

    猜你喜欢
    • 2016-04-22
    • 2020-11-19
    • 2018-01-03
    • 1970-01-01
    • 2023-03-26
    • 2019-06-29
    相关资源
    最近更新 更多