def load_raw(filename, volsize):
""" inspired by mhd_utils from github"""
dim = 3
element_channels = 1
np_type = np.ubyte
arr = list(volsize)
volume = np.prod(arr[0:dim - 1])
shape = (arr[dim - 1], volume, element_channels)
with open(filename,'rb') as fid:
data = np.fromfile(fid, count=np.prod(shape),dtype = np_type)
data.shape = shape
arr.reverse()
data = data.reshape(arr)
return data
python类ubyte()的实例源码
volume_raycasting_example.py 文件源码
项目:ModernGL-Volume-Raycasting-Example
作者: ulricheck
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
def getColors(self, mode=None):
"""Return list of all color stops converted to the specified mode.
If mode is None, then no conversion is done."""
if isinstance(mode, basestring):
mode = self.enumMap[mode.lower()]
color = self.color
if mode in [self.BYTE, self.QCOLOR] and color.dtype.kind == 'f':
color = (color * 255).astype(np.ubyte)
elif mode == self.FLOAT and color.dtype.kind != 'f':
color = color.astype(float) / 255.
if mode == self.QCOLOR:
color = [QtGui.QColor(*x) for x in color]
return color
def getStops(self, mode):
## Get fully-expanded set of RGBA stops in either float or byte mode.
if mode not in self.stopsCache:
color = self.color
if mode == self.BYTE and color.dtype.kind == 'f':
color = (color * 255).astype(np.ubyte)
elif mode == self.FLOAT and color.dtype.kind != 'f':
color = color.astype(float) / 255.
## to support HSV mode, we need to do a little more work..
#stops = []
#for i in range(len(self.pos)):
#pos = self.pos[i]
#color = color[i]
#imode = self.mode[i]
#if imode == self.RGB:
#stops.append((x,color))
#else:
#ns =
self.stopsCache[mode] = (self.pos, color)
return self.stopsCache[mode]
def getLookupTable(self, nPts, alpha=None):
"""
Return an RGB(A) lookup table (ndarray).
============== ============================================================================
**Arguments:**
nPts The number of points in the returned lookup table.
alpha True, False, or None - Specifies whether or not alpha values are included
in the table.If alpha is None, alpha will be automatically determined.
============== ============================================================================
"""
if alpha is None:
alpha = self.usesAlpha()
if alpha:
table = np.empty((nPts,4), dtype=np.ubyte)
else:
table = np.empty((nPts,3), dtype=np.ubyte)
for i in range(nPts):
x = float(i)/(nPts-1)
color = self.getColor(x, toQColor=False)
table[i] = color[:table.shape[1]]
return table
def test_rescaleData():
dtypes = map(np.dtype, ('ubyte', 'uint16', 'byte', 'int16', 'int', 'float'))
for dtype1 in dtypes:
for dtype2 in dtypes:
data = (np.random.random(size=10) * 2**32 - 2**31).astype(dtype1)
for scale, offset in [(10, 0), (10., 0.), (1, -50), (0.2, 0.5), (0.001, 0)]:
if dtype2.kind in 'iu':
lim = np.iinfo(dtype2)
lim = lim.min, lim.max
else:
lim = (-np.inf, np.inf)
s1 = np.clip(float(scale) * (data-float(offset)), *lim).astype(dtype2)
s2 = pg.rescaleData(data, scale, offset, dtype2)
assert s1.dtype == s2.dtype
if dtype2.kind in 'iu':
assert np.all(s1 == s2)
else:
assert np.allclose(s1, s2)
def getStops(self, mode):
## Get fully-expanded set of RGBA stops in either float or byte mode.
if mode not in self.stopsCache:
color = self.color
if mode == self.BYTE and color.dtype.kind == 'f':
color = (color * 255).astype(np.ubyte)
elif mode == self.FLOAT and color.dtype.kind != 'f':
color = color.astype(float) / 255.
## to support HSV mode, we need to do a little more work..
#stops = []
#for i in range(len(self.pos)):
#pos = self.pos[i]
#color = color[i]
#imode = self.mode[i]
#if imode == self.RGB:
#stops.append((x,color))
#else:
#ns =
self.stopsCache[mode] = (self.pos, color)
return self.stopsCache[mode]
def getLookupTable(self, nPts, alpha=None):
"""
Return an RGB(A) lookup table (ndarray).
============== ============================================================================
**Arguments:**
nPts The number of points in the returned lookup table.
alpha True, False, or None - Specifies whether or not alpha values are included
in the table.If alpha is None, alpha will be automatically determined.
============== ============================================================================
"""
if alpha is None:
alpha = self.usesAlpha()
if alpha:
table = np.empty((nPts,4), dtype=np.ubyte)
else:
table = np.empty((nPts,3), dtype=np.ubyte)
for i in range(nPts):
x = float(i)/(nPts-1)
color = self.getColor(x, toQColor=False)
table[i] = color[:table.shape[1]]
return table
def readQImage(self):
"""
Read the current buffer pixels out as a QImage.
"""
w = self.width()
h = self.height()
self.repaint()
pixels = np.empty((h, w, 4), dtype=np.ubyte)
pixels[:] = 128
pixels[...,0] = 50
pixels[...,3] = 255
glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels)
# swap B,R channels for Qt
tmp = pixels[...,0].copy()
pixels[...,0] = pixels[...,2]
pixels[...,2] = tmp
pixels = pixels[::-1] # flip vertical
img = fn.makeQImage(pixels, transpose=False)
return img
def boolToUbyte(x):
"Convert a boolean vector to a ubyte vector which is much more space efficient."
assert isinstance(x,np.ndarray)
assert x.dtype in [np.bool]
assert len(x.shape) == 1
assert x.shape[0] % 8 == 0
out = 1*x[7::8] + \
2*x[6::8] + \
4*x[5::8] + \
8*x[4::8] + \
16*x[3::8] + \
32*x[2::8] + \
64*x[1::8] + \
128*x[0::8]
out = out.astype(np.ubyte)
return out
def ubyteToBool(x):
"Convert a byte vector to a bool vector."
assert isinstance(x,np.ndarray)
assert x.dtype in [np.ubyte]
assert len(x.shape) == 1
out = np.zeros(x.shape[0]*8,dtype=np.bool)
out[7::8] = 1&x > 0
out[6::8] = 2&x > 0
out[5::8] = 4&x > 0
out[4::8] = 8&x > 0
out[3::8] = 16&x > 0
out[2::8] = 32&x > 0
out[1::8] = 64&x > 0
out[0::8] = 128&x > 0
return out
def load_data(images_url: str, labels_url: str) -> (np.array, np.array):
images_decompressed = downloader(images_url)
# Big endian 4 ????? ???? unsigned int, ?????? ?? 4 ?????
magic, size, rows, cols = struct.unpack(">IIII", images_decompressed[:16])
if magic != 2051:
print("Wrong magic for", images_url, "Probably file corrupted")
exit(2)
image_data = np.array(np.frombuffer(images_decompressed[16:], dtype=np.dtype((np.ubyte, (rows * cols,)))) / 255,
dtype=np.float32)
labels_decompressed = downloader(labels_url)
# Big endian 2 ????? ???? unsigned int, ?????? ?? 4 ?????
magic, size = struct.unpack(">II", labels_decompressed[:8])
if magic != 2049:
print("Wrong magic for", labels_url, "Probably file corrupted")
exit(2)
labels = np.frombuffer(labels_decompressed[8:], dtype=np.ubyte)
return image_data, labels
def load_MNIST_images(filename):
"""
returns a 28x28x[number of MNIST images] matrix containing
the raw MNIST images
:param filename: input data file
"""
with open(filename, "r") as f:
magic = np.fromfile(f, dtype=np.dtype('>i4'), count=1)
num_images = int(np.fromfile(f, dtype=np.dtype('>i4'), count=1))
num_rows = int(np.fromfile(f, dtype=np.dtype('>i4'), count=1))
num_cols = int(np.fromfile(f, dtype=np.dtype('>i4'), count=1))
images = np.fromfile(f, dtype=np.ubyte)
images = images.reshape((num_images, num_rows * num_cols)).transpose()
images = images.astype(np.float64) / 255
f.close()
return images
def test_check_argument_list4():
kernel_name = "test_kernel"
kernel_string = """__kernel void test_kernel(__global const ushort number, __global half * factors, __global long * numbers) {
numbers[get_global_id(0)] = numbers[get_global_id(0)] * factors[get_global_id(0)] + number;
}
"""
args = [numpy.uint16(42), numpy.float16([3, 4, 6]), numpy.int64([300]), numpy.ubyte(32)]
try:
check_argument_list(kernel_name, kernel_string, args)
print("Expected a TypeError to be raised")
assert False
except TypeError as expected_error:
print(str(expected_error))
assert "do not match in size" in str(expected_error)
except Exception:
print("Expected a TypeError to be raised")
assert False
def test_sequential_runner_not_matching_answer2():
kernel_string = """__global__ void vector_add(float *c, float *a, float *b, int n) {
int i = blockIdx.x * block_size_x + threadIdx.x;
if (i<n) {
c[i] = a[i] + b[i];
}
} """
args = get_vector_add_args()
answer = [np.ubyte([12]), None, None, None]
tune_params = {"block_size_x": [128 + 64 * i for i in range(5)]}
try:
kernel_tuner.tune_kernel(
"vector_add", kernel_string, args[-1], args, tune_params,
method="diff_evo", verbose=True, answer=answer)
print("Expected a TypeError to be raised")
assert False
except TypeError as expected_error:
print(str(expected_error))
assert "Element 0" in str(expected_error)
except Exception:
print("Expected a TypeError to be raised")
assert False
volume_raycasting_example.py 文件源码
项目:ModernGL-Volume-Raycasting-Example
作者: ulricheck
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
def load_transferfunction(filename):
with open(filename,'rb') as fid:
data = np.fromfile(fid, count=-1,dtype=np.ubyte)
return data
def colorMap(self):
"""Return a ColorMap object representing the current state of the editor."""
if self.colorMode == 'hsv':
raise NotImplementedError('hsv colormaps not yet supported')
pos = []
color = []
for t,x in self.listTicks():
pos.append(x)
c = t.color
color.append([c.red(), c.green(), c.blue(), c.alpha()])
return ColorMap(np.array(pos), np.array(color, dtype=np.ubyte))
def saveFailedTest(data, expect, filename):
"""Upload failed test images to web server to allow CI test debugging.
"""
commit = runSubprocess(['git', 'rev-parse', 'HEAD'])
name = filename.split('/')
name.insert(-1, commit.strip())
filename = '/'.join(name)
host = 'data.pyqtgraph.org'
# concatenate data, expect, and diff into a single image
ds = data.shape
es = expect.shape
shape = (max(ds[0], es[0]) + 4, ds[1] + es[1] + 8 + max(ds[1], es[1]), 4)
img = np.empty(shape, dtype=np.ubyte)
img[..., :3] = 100
img[..., 3] = 255
img[2:2+ds[0], 2:2+ds[1], :ds[2]] = data
img[2:2+es[0], ds[1]+4:ds[1]+4+es[1], :es[2]] = expect
diff = makeDiffImage(data, expect)
img[2:2+diff.shape[0], -diff.shape[1]-2:-2] = diff
png = makePng(img)
conn = httplib.HTTPConnection(host)
req = urllib.urlencode({'name': filename,
'data': base64.b64encode(png)})
conn.request('POST', '/upload.py', req)
response = conn.getresponse().read()
conn.close()
print("\nImage comparison failed. Test result: %s %s Expected result: "
"%s %s" % (data.shape, data.dtype, expect.shape, expect.dtype))
print("Uploaded to: \nhttp://%s/data/%s" % (host, filename))
if not response.startswith(b'OK'):
print("WARNING: Error uploading data to %s" % host)
print(response)
def makeDiffImage(im1, im2):
"""Return image array showing the differences between im1 and im2.
Handles images of different shape. Alpha channels are not compared.
"""
ds = im1.shape
es = im2.shape
diff = np.empty((max(ds[0], es[0]), max(ds[1], es[1]), 4), dtype=int)
diff[..., :3] = 128
diff[..., 3] = 255
diff[:ds[0], :ds[1], :min(ds[2], 3)] += im1[..., :3]
diff[:es[0], :es[1], :min(es[2], 3)] -= im2[..., :3]
diff = np.clip(diff, 0, 255).astype(np.ubyte)
return diff
def test(self, im1, im2, message):
"""Ask the user to decide whether an image test passes or fails.
This method displays the test image, reference image, and the difference
between the two. It then blocks until the user selects the test output
by clicking a pass/fail button or typing p/f. If the user fails the test,
then an exception is raised.
"""
self.show()
if im2 is None:
message += '\nImage1: %s %s Image2: [no standard]' % (im1.shape, im1.dtype)
im2 = np.zeros((1, 1, 3), dtype=np.ubyte)
else:
message += '\nImage1: %s %s Image2: %s %s' % (im1.shape, im1.dtype, im2.shape, im2.dtype)
self.label.setText(message)
self.views[0].image.setImage(im1)
self.views[1].image.setImage(im2)
diff = makeDiffImage(im1, im2)
self.views[2].image.setImage(diff)
self.views[0].autoRange()
while True:
QtGui.QApplication.processEvents()
lastKey = self.lastKey
self.lastKey = None
if lastKey in ('f', 'esc') or not self.isVisible():
raise Exception("User rejected test result.")
elif lastKey == 'p':
break
time.sleep(0.03)
for v in self.views:
v.image.setImage(np.zeros((1, 1, 3), dtype=np.ubyte))
def initializeGL(self):
## Generate texture for rendering points
w = 64
def fn(x,y):
r = ((x-w/2.)**2 + (y-w/2.)**2) ** 0.5
return 255 * (w/2. - np.clip(r, w/2.-1.0, w/2.))
pData = np.empty((w, w, 4))
pData[:] = 255
pData[:,:,3] = np.fromfunction(fn, pData.shape[:2])
#print pData.shape, pData.min(), pData.max()
pData = pData.astype(np.ubyte)
if getattr(self, "pointTexture", None) is None:
self.pointTexture = glGenTextures(1)
glActiveTexture(GL_TEXTURE0)
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.pointTexture)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pData.shape[0], pData.shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, pData)
self.shader = shaders.getShaderProgram('pointSprite')
#def getVBO(self, name):
#if name not in self.vbo:
#self.vbo[name] = vbo.VBO(getattr(self, name).astype('f'))
#return self.vbo[name]
#def setupGLState(self):
#"""Prepare OpenGL state for drawing. This function is called immediately before painting."""
##glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ## requires z-sorting to render properly.
#glBlendFunc(GL_SRC_ALPHA, GL_ONE)
#glEnable( GL_BLEND )
#glEnable( GL_ALPHA_TEST )
#glDisable( GL_DEPTH_TEST )
##glEnable( GL_POINT_SMOOTH )
##glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
##glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, (0, 0, -1e-3))
##glPointParameterfv(GL_POINT_SIZE_MAX, (65500,))
##glPointParameterfv(GL_POINT_SIZE_MIN, (0,))
def imageToArray(img, copy=False, transpose=True):
"""
Convert a QImage into numpy array. The image must have format RGB32, ARGB32, or ARGB32_Premultiplied.
By default, the image is not copied; changes made to the array will appear in the QImage as well (beware: if
the QImage is collected before the array, there may be trouble).
The array will have shape (width, height, (b,g,r,a)).
"""
fmt = img.format()
ptr = img.bits()
if USE_PYSIDE:
arr = np.frombuffer(ptr, dtype=np.ubyte)
else:
ptr.setsize(img.byteCount())
arr = np.asarray(ptr)
if img.byteCount() != arr.size * arr.itemsize:
# Required for Python 2.6, PyQt 4.10
# If this works on all platforms, then there is no need to use np.asarray..
arr = np.frombuffer(ptr, np.ubyte, img.byteCount())
arr = arr.reshape(img.height(), img.width(), 4)
if fmt == img.Format_RGB32:
arr[...,3] = 255
if copy:
arr = arr.copy()
if transpose:
return arr.transpose((1,0,2))
else:
return arr
def colorMap(self):
"""Return a ColorMap object representing the current state of the editor."""
if self.colorMode == 'hsv':
raise NotImplementedError('hsv colormaps not yet supported')
pos = []
color = []
for t,x in self.listTicks():
pos.append(x)
c = t.color
color.append([c.red(), c.green(), c.blue(), c.alpha()])
return ColorMap(np.array(pos), np.array(color, dtype=np.ubyte))
def saveFailedTest(data, expect, filename):
"""Upload failed test images to web server to allow CI test debugging.
"""
commit = runSubprocess(['git', 'rev-parse', 'HEAD'])
name = filename.split('/')
name.insert(-1, commit.strip())
filename = '/'.join(name)
host = 'data.pyqtgraph.org'
# concatenate data, expect, and diff into a single image
ds = data.shape
es = expect.shape
shape = (max(ds[0], es[0]) + 4, ds[1] + es[1] + 8 + max(ds[1], es[1]), 4)
img = np.empty(shape, dtype=np.ubyte)
img[..., :3] = 100
img[..., 3] = 255
img[2:2+ds[0], 2:2+ds[1], :ds[2]] = data
img[2:2+es[0], ds[1]+4:ds[1]+4+es[1], :es[2]] = expect
diff = makeDiffImage(data, expect)
img[2:2+diff.shape[0], -diff.shape[1]-2:-2] = diff
png = makePng(img)
conn = httplib.HTTPConnection(host)
req = urllib.urlencode({'name': filename,
'data': base64.b64encode(png)})
conn.request('POST', '/upload.py', req)
response = conn.getresponse().read()
conn.close()
print("\nImage comparison failed. Test result: %s %s Expected result: "
"%s %s" % (data.shape, data.dtype, expect.shape, expect.dtype))
print("Uploaded to: \nhttp://%s/data/%s" % (host, filename))
if not response.startswith(b'OK'):
print("WARNING: Error uploading data to %s" % host)
print(response)
def makeDiffImage(im1, im2):
"""Return image array showing the differences between im1 and im2.
Handles images of different shape. Alpha channels are not compared.
"""
ds = im1.shape
es = im2.shape
diff = np.empty((max(ds[0], es[0]), max(ds[1], es[1]), 4), dtype=int)
diff[..., :3] = 128
diff[..., 3] = 255
diff[:ds[0], :ds[1], :min(ds[2], 3)] += im1[..., :3]
diff[:es[0], :es[1], :min(es[2], 3)] -= im2[..., :3]
diff = np.clip(diff, 0, 255).astype(np.ubyte)
return diff
def test(self, im1, im2, message):
"""Ask the user to decide whether an image test passes or fails.
This method displays the test image, reference image, and the difference
between the two. It then blocks until the user selects the test output
by clicking a pass/fail button or typing p/f. If the user fails the test,
then an exception is raised.
"""
self.show()
if im2 is None:
message += '\nImage1: %s %s Image2: [no standard]' % (im1.shape, im1.dtype)
im2 = np.zeros((1, 1, 3), dtype=np.ubyte)
else:
message += '\nImage1: %s %s Image2: %s %s' % (im1.shape, im1.dtype, im2.shape, im2.dtype)
self.label.setText(message)
self.views[0].image.setImage(im1)
self.views[1].image.setImage(im2)
diff = makeDiffImage(im1, im2)
self.views[2].image.setImage(diff)
self.views[0].autoRange()
while True:
QtGui.QApplication.processEvents()
lastKey = self.lastKey
self.lastKey = None
if lastKey in ('f', 'esc') or not self.isVisible():
raise Exception("User rejected test result.")
elif lastKey == 'p':
break
time.sleep(0.03)
for v in self.views:
v.image.setImage(np.zeros((1, 1, 3), dtype=np.ubyte))
def initializeGL(self):
## Generate texture for rendering points
w = 64
def fn(x,y):
r = ((x-w/2.)**2 + (y-w/2.)**2) ** 0.5
return 255 * (w/2. - np.clip(r, w/2.-1.0, w/2.))
pData = np.empty((w, w, 4))
pData[:] = 255
pData[:,:,3] = np.fromfunction(fn, pData.shape[:2])
#print pData.shape, pData.min(), pData.max()
pData = pData.astype(np.ubyte)
if getattr(self, "pointTexture", None) is None:
self.pointTexture = glGenTextures(1)
glActiveTexture(GL_TEXTURE0)
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.pointTexture)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pData.shape[0], pData.shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, pData)
self.shader = shaders.getShaderProgram('pointSprite')
#def getVBO(self, name):
#if name not in self.vbo:
#self.vbo[name] = vbo.VBO(getattr(self, name).astype('f'))
#return self.vbo[name]
#def setupGLState(self):
#"""Prepare OpenGL state for drawing. This function is called immediately before painting."""
##glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ## requires z-sorting to render properly.
#glBlendFunc(GL_SRC_ALPHA, GL_ONE)
#glEnable( GL_BLEND )
#glEnable( GL_ALPHA_TEST )
#glDisable( GL_DEPTH_TEST )
##glEnable( GL_POINT_SMOOTH )
##glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
##glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, (0, 0, -1e-3))
##glPointParameterfv(GL_POINT_SIZE_MAX, (65500,))
##glPointParameterfv(GL_POINT_SIZE_MIN, (0,))
def imageToArray(img, copy=False, transpose=True):
"""
Convert a QImage into numpy array. The image must have format RGB32, ARGB32, or ARGB32_Premultiplied.
By default, the image is not copied; changes made to the array will appear in the QImage as well (beware: if
the QImage is collected before the array, there may be trouble).
The array will have shape (width, height, (b,g,r,a)).
"""
fmt = img.format()
ptr = img.bits()
if USE_PYSIDE:
arr = np.frombuffer(ptr, dtype=np.ubyte)
else:
ptr.setsize(img.byteCount())
arr = np.asarray(ptr)
if img.byteCount() != arr.size * arr.itemsize:
# Required for Python 2.6, PyQt 4.10
# If this works on all platforms, then there is no need to use np.asarray..
arr = np.frombuffer(ptr, np.ubyte, img.byteCount())
arr = arr.reshape(img.height(), img.width(), 4)
if fmt == img.Format_RGB32:
arr[...,3] = 255
if copy:
arr = arr.copy()
if transpose:
return arr.transpose((1,0,2))
else:
return arr
def parse(x):
#parse the digits file into tuples of
digit = loads(x)
array = np.fromstring(b64decode(digit["data"]),dtype=np.ubyte)
array = array.astype(np.float64)
return (digit["label"], array)
def setup_textures(gltf, uri_path):
# TODO: support data URIs
pil_images = {}
for image_name, image in gltf.get('images', {}).items():
filename = os.path.join(uri_path, image['uri'])
pil_image = Image.open(filename)
pil_images[image_name] = pil_image
_logger.debug('* loaded image "%s" (from %s)', image_name, filename)
for texture_name, texture in gltf.get('textures', {}).items():
sampler = gltf['samplers'][texture['sampler']]
texture_id = gl.glGenTextures(1)
gl.glBindTexture(texture['target'], texture_id)
sampler_id = gl.glGenSamplers(1)
gl.glSamplerParameteri(sampler_id, gl.GL_TEXTURE_MIN_FILTER, sampler.get('minFilter', 9986))
gl.glSamplerParameteri(sampler_id, gl.GL_TEXTURE_MAG_FILTER, sampler.get('magFilter', 9729))
gl.glSamplerParameteri(sampler_id, gl.GL_TEXTURE_WRAP_S, sampler.get('wrapS', 10497))
gl.glSamplerParameteri(sampler_id, gl.GL_TEXTURE_WRAP_T, sampler.get('wrapT', 10497))
sampler['id'] = sampler_id
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
if texture['type'] != gl.GL_UNSIGNED_BYTE:
raise Exception('TODO')
gl.glTexImage2D(texture['target'], 0,
texture['internalFormat'],
pil_image.width, pil_image.height, 0,
gl.GL_RGB, #texture['format'], # INVESTIGATE
texture['type'],
np.array(list(pil_image.getdata()), dtype=(np.ubyte if texture['type'] == gl.GL_UNSIGNED_BYTE else np.ushort)))
gl.glGenerateMipmap(texture['target'])
if gl.glGetError() != gl.GL_NO_ERROR:
raise Exception('failed to create texture "%s"' % texture_name)
texture['id'] = texture_id
_logger.debug('* created texture "%s"', texture_name)
def hamming(a,b):
if a.dtype == np.bool and b.dtype == bool:
return (a ^ b).sum()
elif a.dtype == np.ubyte and b.dtype == np.ubyte:
return hamming_table[a^b].sum()
else:
raise NotImplementedError("Unsupported array types %s and %s",a.dtype,b.dtype)