Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've spent the last week playing around with using NumPy to generate random textures. I came across this post and tried the accepted answers.</p> <p>I can confirm that the previously accepted answer is <strong>NOT CORRECT</strong>.</p> <p>It seems correct because you are using grey-scale images. But if you were to use a colour image (RGBA for example) and zero the GBA channels you would have discovered this because you would still be getting green and blue showing up in your texture.</p> <p>By using __str__() you are actually sending garbage and not the values you really want.</p> <p>I'll use my code to demonstrate this.</p> <pre><code>import numpy import pyglet from pyglet.gl import * # the size of our texture dimensions = (16, 16) # we need RGBA textures # which has 4 channels format_size = 4 bytes_per_channel = 1 # populate our array with some random data data = numpy.random.random_integers( low = 0, high = 1, size = (dimensions[ 0 ] * dimensions[ 1 ], format_size) ) # convert any 1's to 255 data *= 255 # set the GB channels (from RGBA) to 0 data[ :, 1:-1 ] = 0 # ensure alpha is always 255 data[ :, 3 ] = 255 # we need to flatten the array data.shape = -1 </code></pre> <p>Using the answer above, you would do the following</p> <h1>DON'T DO THIS!</h1> <pre><code>tex_data = data.astype('uint8').__str__() </code></pre> <p>If you try the code out, you will get all colours, not just red!</p> <h1>Do this instead!</h1> <p>The proper way is to convert to the ctype GLubytes.</p> <pre><code># convert to GLubytes tex_data = (GLubyte * data.size)( *data.astype('uint8') ) </code></pre> <p>You can then pass this into your texture.</p> <pre><code># create an image # pitch is 'texture width * number of channels per element * per channel size in bytes' return pyglet.image.ImageData( dimensions[ 0 ], dimensions[ 1 ], "RGBA", tex_data, pitch = dimensions[ 1 ] * format_size * bytes_per_channel ) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload