Python From array of floats to texture

808 Views Asked by At

I need to create a texture from matrix of floats([0..1]). Texture should show a grey squares, but only show a white rectangle :(

I have this code:

def _generate_image(self):
    i_len = len(self._data)*Config().get_pixels_per_tile()
    j_len = len(self._data[0])*Config().get_pixels_per_tile()
    data =  ''.join([ chr(int(c*255)) for f in self._data for c in f for _ in range(3*Config().get_pixels_per_tile()) ])
    print data
    return ImageFromData(data, j_len, i_len, GL_RGB, GL_UNSIGNED_BYTE)


class ImageFromData(object):
    def __init__(self, data, width, height, colors, type_):
        self.w = width
        self.h = height
        self.image = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, self.image)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexImage2D( GL_TEXTURE_2D, 0, colors, width, height, 0, colors, type_, data )

Thanks!

1

There are 1 best solutions below

0
On

I think you might be making a mistake while converting your image to a string in that nasty-looking set of nested for loops you have there :-)

So your original data are two nested lists of float intensity values for rows and columns of pixels, and you're going to copy them three times to fill the RGB channels? I think you want this:

def pixlist2string(pixlist):
    tmp = []
    for row in pixlist:
        for pix in row:
            for channel in xrange(3):
                tmp.append(chr(int(255*pix)))
    return ''.join(ss for ss in tmp)

This is a very roundabout way of doing things, though. Converting to 8-bit integers is unnecessary - just tell glTexImage2D that the input data type is GL_FLOAT and give it normalised values between 0 and 1. Similarly there's no need to duplicate input pixels in order to fill RGB channels if you set the input format to single-channel (GL_INTENSITY,GL_LUMINANCE, GL_RED etc).

I would also strongly recommend using Numpy arrays to hold your input pixel data. Then you can just pass the array itself to glTexImage2D without fiddling around with string conversion.