How to create an unsigned char array in Python? (For glReadPixels using PyOpenGL)

Viewed 591

I have written some code in GLES2 and EGL using PyOpenGL, I need to use the glReadPixels function except the last argument must be a ctypes unsigned char buffer which I'm not sure how to create.

Here is the C code:

unsigned char* buffer = malloc(width * height * 4);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

What would the equivalent Python code be?

I am using GLES2 and not GL, therefore, buffer = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE) does not work.

When I try buffer = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE) I get the following error:

   buffer = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE)
  File "/home/fa/berryconda3/lib/python3.6/site-packages/OpenGL/platform/baseplatform.py", line 415, in __call__
    return self( *args, **named )
TypeError: this function takes at least 7 arguments (6 given)
1 Answers

Create a byte buffer with the proper size:

buffer_size = width * height * 4
buffer = (GLbyte * buffer_size)()

Pass the buffer glReadPixels:

glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer)

That's the same as using ctypes.c_byte:

import ctypes
buffer_size = width * height * 4
buffer = (ctypes.c_byte * buffer_size)()

Or create a numpy buffer with the proper size:

import numpy
buffer = numpy.empty(width * height * 4, "uint8")

Pass the buffer glReadPixels:

glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer)
Related