JavaEar 专注于收集分享传播有价值的技术资料

Converting multi-dimensional array to a tuple in python

I am getting some frame data from a web cam in the form of rgb values.

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

The output is (480, 640, 3). Now I want to construct image from these values. So, I want to use

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

But, here the third argument takes a tuple. I get this error

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

So, my question is what is the best way to convert this frame data to a tuple, so that I can construct my image.

2个回答

    最佳答案
  1. I am assuming here that you are importing the class Image from PIL.

    The documentation for Image.new(), accessed with console command Image.new? is:

    In [3]: Image.new?
    Type: function
    Base Class:
    String Form:
    Namespace: Interactive
    File: /usr/lib/python2.7/dist-packages/PIL/Image.py
    Definition: Image.new(mode, size, color=0)
    Docstring: Create a new image

    The third parameter is an RGB color, such as (255,255,255), to fill the hole image. You can't initialize individual pixels with this function.

    I am also assuming that frame is a 3D array. As your output suggests, it's 480 lines and 640 rows of RGB tuples.

    I don't know if there is a simpler way to do this, but I would set the pixel values by the putpixel() function, something like:

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

    Always check the docstring via console, it saves a lot of time. I also recommend using ipython as your console.

  2. 参考答案2
  3. I found this implementation to be faster

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