Here are the examples of the python api numpy.ubyte taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
52 Examples
5
Example 1
Project: f2py Source File: utils.py
def get_char_bit():
import numpy
one = numpy.ubyte(1)
two = numpy.ubyte(2)
n = numpy.ubyte(2)
i = 1
while n>=two:
n <<= one
i += 1
return i
3
Example 2
def nz(x):
x = asarray(x,dtype=nx.ubyte)
if x.ndim != 1:
raise TypeError, "intput must have 1 dimension."
indxs = nx.flatnonzero(x != 0)
return indxs[-1].item()+1
3
Example 3
def toarray (self, target = None):
sz = self.get_size()
if target is None:
target = numpy.zeros((sz,), dtype=numpy.ubyte)
dtype = target.dtype
target[:4].view(dtype=numpy.uint32)[0] = sz
target[4:4+8].view(dtype=numpy.float64)[0] = self.time
target[12:16].view (dtype=numpy.uint32)[0] = self.type
target[16:20].view (dtype=numpy.uint32)[0] = self.record[3]
l = len (self.description)
target[20:20+l] = numpy.array([self.description]).view(dtype=dtype)
target[20+l] = 0
return target
3
Example 4
def _update(self):
""" Upload all pending data to GPU. """
if self.pending_data:
start, stop = self.pending_data
offset, nbytes = start, stop-start
# offset, nbytes = self.pending_data
data = self.ravel().view(np.ubyte)[offset:offset+nbytes]
gl.glBufferSubData(self.target, offset, nbytes, data)
self._pending_data = None
self._need_update = False
3
Example 5
def toarray (self, target=None):
sz = self.get_size()
if target is None:
target = numpy.zeros((sz,), dtype=numpy.ubyte)
dtype = target.dtype
target[:4].view(dtype=numpy.int32)[0] = len(self.ranges)
data = numpy.array(self.ranges).ravel()
target[4:4+data.nbytes] = data.view (dtype=dtype)
return target
3
Example 6
Project: pylibtiff Source File: test_bittools.py
def test_setgetword():
for dtype in [numpy.ubyte, numpy.int32, numpy.float64]:
arr = numpy.array(list(range(-256,256)), dtype=dtype)
arr2 = numpy.zeros(arr.shape, dtype=arr.dtype)
for i in range (arr.nbytes):
word, next = bittools.getword (arr,i*8,8)
bittools.setword (arr2,i*8,8,word)
assert (arr==arr2).all(),repr((arr,arr2))
print('ok')
3
Example 7
Project: vispy Source File: test_image.py
def test_make_png():
""" Test to ensure that make_png functions correctly.
"""
# Save random RGBA and RGB arrays onto disk as PNGs using make_png.
# Read them back with an image library and check whether the array
# saved is equal to the array read.
# Create random RGBA array as type ubyte
rgba_save = np.random.randint(256, size=(100, 100, 4)).astype(np.ubyte)
# Get rid of the alpha for RGB
rgb_save = rgba_save[:, :, :3]
# Output file should be in temp
png_out = op.join(temp_dir, 'random.png')
# write_png implicitly tests _make_png
for rgb_a in (rgba_save, rgb_save):
write_png(png_out, rgb_a)
rgb_a_read = read_png(png_out)
assert_array_equal(rgb_a, rgb_a_read)
3
Example 8
Project: vispy Source File: datasets.py
def pack_unit(value):
"""Packs float values between [0,1] into 4 unsigned int8
Returns
-------
pack: array
packed interpolation kernel
"""
pack = np.zeros(value.shape + (4,), dtype=np.ubyte)
for i in range(4):
value, pack[..., i] = np.modf(value * 256.)
return pack
3
Example 9
def toarray(self, target=None):
sz = self.get_size()
if target is None:
target = numpy.zeros((sz,), dtype=numpy.ubyte)
dtype = target.dtype
header = numpy.array([sz, self.stamps.size], dtype=numpy.int32).view(dtype=dtype)
assert header.nbytes==8,repr(header.nbytes)
data = self.stamps.view(dtype=dtype)
target[:header.nbytes] = header
target[header.nbytes:header.nbytes+data.nbytes] = data
return target
3
Example 10
def __init__(self, tag):
if isinstance(tag, str):
tag = tag_name2value[tag]
assert isinstance(tag, int), repr(tag)
self.tag = tag
self.type_name = tag_value2type[tag]
self.type = name2type[self.type_name]
self.type_nbytes = type2bytes[self.type]
self.type_dtype = type2dtype[self.type]
self.tag_name = tag_value2name.get(self.tag,
'TAG%s' % (hex(self.tag),))
self.record = numpy.zeros((12,), dtype=numpy.ubyte)
self.record[:2].view(dtype=numpy.uint16)[0] = self.tag
self.record[2:4].view(dtype=numpy.uint16)[0] = self.type
self.values = []
3
Example 11
def toarray (self, target=None):
sz = self.get_size()
if target is None:
target = numpy.zeros((sz,), dtype=numpy.ubyte)
dtype = target.dtype
header = numpy.array([sz, len (self.events)], dtype=numpy.int32).view(dtype=dtype)
target[:header.nbytes] = header
offset = header.nbytes
for event in self.events:
event.toarray(target[offset:])
offset += event.get_size()
return target
3
Example 12
def toarray(self, target=None):
sz = self.get_size()
if target is None:
target = numpy.zeros((sz,), dtype=numpy.ubyte)
dtype = target.dtype
target[:self.data.nbytes] = self.data.view(dtype=dtype)
return target
3
Example 13
@property
def data(self):
if self._data is None:
channels = self.ifdentry.value['DimensionChannels']
sz = channels * 4
self._data = self.ifdentry.tiff.get_values(self.offset, numpy.ubyte, sz)
return self._data
3
Example 14
def toarray(self, target=None, new_offset=None):
sz = self.get_size()
if target is None:
target = numpy.zeros((sz,), dtype = numpy.ubyte)
if new_offset is None:
new_offset = self.offset
offset_diff = new_offset - self.offset
dtype = target.dtype
target[:sz] = self.ifdentry.tiff.data[self.offset:self.offset + sz]
return target
3
Example 15
Project: git-vanity Source File: git_vanity.py
def sha1_preprocess_data(data):
size = get_padded_size(len(data))
preprocessed_message = np.zeros(size, dtype=np.ubyte)
preprocessed_message[:len(data)] = list(data)
preprocessed_message[len(data)] = 0x80
preprocessed_message[-8:] = list(struct.pack('>Q', len(data)*8))
return preprocessed_message
3
Example 16
Project: vispy Source File: datasets.py
def pack_ieee(value):
"""Packs float ieee binary representation into 4 unsigned int8
Returns
-------
pack: array
packed interpolation kernel
"""
return np.fromstring(value.tostring(),
np.ubyte).reshape((value.shape + (4,)))
3
Example 17
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
0
Example 18
def load(self, charcodes = ''):
'''
Build glyphs corresponding to individual characters in charcodes.
Parameters:
-----------
charcodes: [str | unicode]
Set of characters to be represented
'''
face = freetype.Face( self.filename )
pen = freetype.Vector(0,0)
hres = 100*72
hscale = 1.0/100
for charcode in charcodes:
face.set_char_size( int(self.size * 64), 0, hres, 72 )
matrix = freetype.Matrix( int((hscale) * 0x10000), int((0.0) * 0x10000),
int((0.0) * 0x10000), int((1.0) * 0x10000) )
face.set_transform( matrix, pen )
if charcode in self.glyphs.keys():
continue
flags = freetype.FT_LOAD_RENDER | freetype.FT_LOAD_FORCE_AUTOHINT
flags |= freetype.FT_LOAD_TARGET_LCD
face.load_char( charcode, flags )
bitmap = face.glyph.bitmap
left = face.glyph.bitmap_left
top = face.glyph.bitmap_top
width = face.glyph.bitmap.width
rows = face.glyph.bitmap.rows
pitch = face.glyph.bitmap.pitch
w = width/3
h = rows
# h+1,w+1 to have a black border
region = self.atlas.allocate( (h+1,w+1) )
if region is None:
log.warn("Cannot store glyph '%c'" % charcode)
continue
x,y,_,_ = region
# sould be y+h+1,x+w+1 but we skip the black border
texture = self.atlas[y:y+h,x:x+w]
data = []
for i in range(rows):
data.extend(bitmap.buffer[i*pitch:i*pitch+width])
data = np.array(data,dtype=np.ubyte).reshape(h,w,3)
texture[...] = data
# Build glyph
size = w,h
offset = left, top
advance= face.glyph.advance.x, face.glyph.advance.y
u0 = (x + 0.0)/float(self.atlas.width)
v0 = (y + 0.0)/float(self.atlas.height)
u1 = (x + w - 0.0)/float(self.atlas.width)
v1 = (y + h - 0.0)/float(self.atlas.height)
texcoords = (u0,v0,u1,v1)
glyph = Glyph(charcode, size, offset, advance, texcoords)
self.glyphs[charcode] = glyph
# Generate kerning
for g in self.glyphs.values():
# 64 * 64 because of 26.6 encoding AND the transform matrix used
# in texture_font_load_face (hres = 64)
kerning = face.get_kerning(g.charcode, charcode,
mode=freetype.FT_KERNING_UNFITTED)
if kerning.x != 0:
glyph.kerning[g.charcode] = kerning.x/(64.0*64.0)
kerning = face.get_kerning(charcode, g.charcode,
mode=freetype.FT_KERNING_UNFITTED)
if kerning.x != 0:
g.kerning[charcode] = kerning.x/(64.0*64.0)
0
Example 19
def buildAtlas(self):
# get rendered array for all symbols, keep track of avg/max width
rendered = {}
avgWidth = 0.0
maxWidth = 0
images = []
for key, sourceRect in self.symbolMap.items():
if sourceRect.width() == 0:
img = renderSymbol(key[0], key[1], sourceRect.pen, sourceRect.brush)
images.append(img) ## we only need this to prevent the images being garbage collected immediately
arr = fn.imageToArray(img, copy=False, transpose=False)
else:
(y,x,h,w) = sourceRect.getRect()
arr = self.atlasData[x:x+w, y:y+w]
rendered[key] = arr
w = arr.shape[0]
avgWidth += w
maxWidth = max(maxWidth, w)
nSymbols = len(rendered)
if nSymbols > 0:
avgWidth /= nSymbols
width = max(maxWidth, avgWidth * (nSymbols**0.5))
else:
avgWidth = 0
width = 0
# sort symbols by height
symbols = sorted(rendered.keys(), key=lambda x: rendered[x].shape[1], reverse=True)
self.atlasRows = []
x = width
y = 0
rowheight = 0
for key in symbols:
arr = rendered[key]
w,h = arr.shape[:2]
if x+w > width:
y += rowheight
x = 0
rowheight = h
self.atlasRows.append([y, rowheight, 0])
self.symbolMap[key].setRect(y, x, h, w)
x += w
self.atlasRows[-1][2] = x
height = y + rowheight
self.atlasData = np.zeros((width, height, 4), dtype=np.ubyte)
for key in symbols:
y, x, h, w = self.symbolMap[key].getRect()
self.atlasData[x:x+w, y:y+h] = rendered[key]
self.atlas = None
self.atlasValid = True
self.max_width = maxWidth
0
Example 20
def _load(self, charcodes, face):
pen = Vector(0,0)
hres = 16*72
hscale = 1.0/16
# todo: use set_pixel_sizes?
for charcode in charcodes:
face.set_char_size( int(self.size * 64), 0, hres, 72 )
matrix = Matrix( int((hscale) * n2_16), int((0.0) * n2_16),
int((0.0) * n2_16), int((1.0) * n2_16) )
face.set_transform( matrix, pen )
if charcode in self.glyphs.keys():
continue
self.dirty = True
flags = FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT
face.load_char( charcode, flags )
bitmap = face.glyph.bitmap
left = face.glyph.bitmap_left
top = face.glyph.bitmap_top
width = face.glyph.bitmap.width
rows = face.glyph.bitmap.rows
pitch = face.glyph.bitmap.pitch
padding = 1 # Extra space for neighboring pixels to join in aa
margin = 1 # Extra space to prevent overlap from other glyphs
padmarg = padding + margin
x,y,w,h = self.atlas.get_region(width/self.depth+2*padmarg,
rows+2*padmarg)
if x < 0:
print('Missed !')
continue
x,y = x+padmarg, y+padmarg
w,h = w-2*padmarg, h-2*padmarg
data = []
for i in range(rows):
data.extend(bitmap.buffer[i*pitch:i*pitch+width])
data = np.array(data,dtype=np.ubyte).reshape(h,w,self.depth)
gamma = 1.5
Z = ((data/255.0)**(gamma))
data = (Z*255).astype(np.ubyte)
if True: # Add an extra pixel, otherwise there's no room for the aa
# Note that we can do this because we asked for a larger region anyway
data2 = np.zeros(( data.shape[0]+2*padding,
data.shape[1]+2*padding,
data.shape[2]), np.ubyte)
data2[padding:-padding,padding:-padding,:] = data
data = data2
x,y = x-padding, y-padding
w,h = w+2*padding, h+2*padding
self.atlas.set_region((x,y,w,h), data)
# Build glyph
size = w,h
offset = left, top
advance= face.glyph.advance.x, face.glyph.advance.y
u0 = (x + 0.0)/float(self.atlas.width)
v0 = (y + 0.0)/float(self.atlas.height)
u1 = (x + w - 0.0)/float(self.atlas.width)
v1 = (y + h - 0.0)/float(self.atlas.height)
texcoords = (u0,v0,u1,v1)
glyph = TextureGlyph(charcode, size, offset, advance, texcoords)
self.glyphs[charcode] = glyph
# Generate kerning
for g in self.glyphs.values():
# 64 * 64 because of 26.6 encoding AND the transform matrix used
# in texture_font_load_face (hres = 64)
kerning = face.get_kerning(g.charcode, charcode, mode=FT_KERNING_UNFITTED)
if kerning.x != 0:
glyph.kerning[g.charcode] = kerning.x/(64.0*64.0)
kerning = face.get_kerning(charcode, g.charcode, mode=FT_KERNING_UNFITTED)
if kerning.x != 0:
g.kerning[charcode] = kerning.x/(64.0*64.0)
0
Example 21
Project: rasterio Source File: test_read.py
def test_read_out(self):
with rasterio.open('tests/data/RGB.byte.tif') as s:
# regular array, without mask
a = np.empty((3, 718, 791), np.ubyte)
b = s.read(out=a)
self.assertFalse(hasattr(a, 'mask'))
self.assertFalse(hasattr(b, 'mask'))
# with masked array
a = np.ma.empty((3, 718, 791), np.ubyte)
b = s.read(out=a)
self.assertEqual(id(a.data), id(b.data))
# TODO: is there a way to id(a.mask)?
self.assertTrue(hasattr(a, 'mask'))
self.assertTrue(hasattr(b, 'mask'))
# use all parameters
a = np.empty((1, 20, 10), np.ubyte)
b = s.read([2], a, ((310, 330), (320, 330)), False)
self.assertEqual(id(a), id(b))
# pass 2D array with index
a = np.empty((20, 10), np.ubyte)
b = s.read(2, a, ((310, 330), (320, 330)), False)
self.assertEqual(id(a), id(b))
self.assertEqual(a.ndim, 2)
# different data types
a = np.empty((3, 718, 791), np.float64)
self.assertRaises(ValueError, s.read, out=a)
# different number of array dimensions
a = np.empty((20, 10), np.ubyte)
self.assertRaises(ValueError, s.read, [2], out=a)
# different number of array shape in 3D
a = np.empty((2, 20, 10), np.ubyte)
self.assertRaises(ValueError, s.read, [2], out=a)
0
Example 22
def assertImageApproved(image, standardFile, message=None, **kwargs):
"""Check that an image test result matches a pre-approved standard.
If the result does not match, then the user can optionally invoke a GUI
to compare the images and decide whether to fail the test or save the new
image as the standard.
This function will automatically clone the test-data repository into
~/.pyqtgraph/test-data. However, it is up to the user to ensure this repository
is kept up to date and to commit/push new images after they are saved.
Run the test with the environment variable PYQTGRAPH_AUDIT=1 to bring up
the auditing GUI.
Parameters
----------
image : (h, w, 4) ndarray
standardFile : str
The name of the approved test image to check against. This file name
is relative to the root of the pyqtgraph test-data repository and will
be automatically fetched.
message : str
A string description of the image. It is recommended to describe
specific features that an auditor should look for when deciding whether
to fail a test.
Extra keyword arguments are used to set the thresholds for automatic image
comparison (see ``assertImageMatch()``).
"""
if isinstance(image, QtGui.QWidget):
w = image
# just to be sure the widget size is correct (new window may be resized):
QtGui.QApplication.processEvents()
graphstate = scenegraphState(w, standardFile)
image = np.zeros((w.height(), w.width(), 4), dtype=np.ubyte)
qimg = fn.makeQImage(image, alpha=True, copy=False, transpose=False)
painter = QtGui.QPainter(qimg)
w.render(painter)
painter.end()
# transpose BGRA to RGBA
image = image[..., [2, 1, 0, 3]]
if message is None:
code = inspect.currentframe().f_back.f_code
message = "%s::%s" % (code.co_filename, code.co_name)
# Make sure we have a test data repo available, possibly invoking git
dataPath = getTestDataRepo()
# Read the standard image if it exists
stdFileName = os.path.join(dataPath, standardFile + '.png')
if not os.path.isfile(stdFileName):
stdImage = None
else:
pxm = QtGui.QPixmap()
pxm.load(stdFileName)
stdImage = fn.imageToArray(pxm.toImage(), copy=True, transpose=False)
# If the test image does not match, then we go to audit if requested.
try:
if image.shape[2] != stdImage.shape[2]:
raise Exception("Test result has different channel count than standard image"
"(%d vs %d)" % (image.shape[2], stdImage.shape[2]))
if image.shape != stdImage.shape:
# Allow im1 to be an integer multiple larger than im2 to account
# for high-resolution displays
ims1 = np.array(image.shape).astype(float)
ims2 = np.array(stdImage.shape).astype(float)
sr = ims1 / ims2 if ims1[0] > ims2[0] else ims2 / ims1
if (sr[0] != sr[1] or not np.allclose(sr, np.round(sr)) or
sr[0] < 1):
raise TypeError("Test result shape %s is not an integer factor"
" different than standard image shape %s." %
(ims1, ims2))
sr = np.round(sr).astype(int)
image = fn.downsample(image, sr[0], axis=(0, 1)).astype(image.dtype)
assertImageMatch(image, stdImage, **kwargs)
if bool(os.getenv('PYQTGRAPH_PRINT_TEST_STATE', False)):
print(graphstate)
if os.getenv('PYQTGRAPH_AUDIT_ALL') == '1':
raise Exception("Image test passed, but auditing due to PYQTGRAPH_AUDIT_ALL evnironment variable.")
except Exception:
if stdFileName in gitStatus(dataPath):
print("\n\nWARNING: unit test failed against modified standard "
"image %s.\nTo revert this file, run `cd %s; git checkout "
"%s`\n" % (stdFileName, dataPath, standardFile))
if os.getenv('PYQTGRAPH_AUDIT') == '1' or os.getenv('PYQTGRAPH_AUDIT_ALL') == '1':
sys.excepthook(*sys.exc_info())
getTester().test(image, stdImage, message)
stdPath = os.path.dirname(stdFileName)
print('Saving new standard image to "%s"' % stdFileName)
if not os.path.isdir(stdPath):
os.makedirs(stdPath)
img = fn.makeQImage(image, alpha=True, transpose=False)
img.save(stdFileName)
else:
if stdImage is None:
raise Exception("Test standard %s does not exist. Set "
"PYQTGRAPH_AUDIT=1 to add this image." % stdFileName)
else:
if os.getenv('TRAVIS') is not None:
saveFailedTest(image, stdImage, standardFile)
print(graphstate)
raise
0
Example 23
def _arr2img(ar):
""" Convert Numeric array to PIL Image.
"""
return Image.frombytes('L', (ar.shape[1], ar.shape[0]), ar.astype(numpy.ubyte).tostring())
0
Example 24
Project: meshio Source File: vtk_io.py
def _generate_vtk_mesh(points, cells):
import vtk
from vtk.util import numpy_support
mesh = vtk.vtkUnstructuredGrid()
# set points
vtk_points = vtk.vtkPoints()
# Not using a deep copy here results in a segfault.
vtk_array = numpy_support.numpy_to_vtk(points, deep=True)
vtk_points.SetData(vtk_array)
mesh.SetPoints(vtk_points)
# Set cells.
meshio_to_vtk_type = {
'vertex': vtk.VTK_VERTEX,
'line': vtk.VTK_LINE,
'triangle': vtk.VTK_TRIANGLE,
'quad': vtk.VTK_QUAD,
'tetra': vtk.VTK_TETRA,
'hexahedron': vtk.VTK_HEXAHEDRON,
'wedge': vtk.VTK_WEDGE,
'pyramid': vtk.VTK_PYRAMID
}
# create cell_array. It's a one-dimensional vector with
# (num_points2, p0, p1, ... ,pk, numpoints1, p10, p11, ..., p1k, ...
cell_types = []
cell_offsets = []
cell_connectivity = []
len_array = 0
for meshio_type, data in cells.iteritems():
numcells, num_local_nodes = data.shape
vtk_type = meshio_to_vtk_type[meshio_type]
# add cell types
cell_types.append(numpy.empty(numcells, dtype=numpy.ubyte))
cell_types[-1].fill(vtk_type)
# add cell offsets
cell_offsets.append(numpy.arange(
len_array,
len_array + numcells * (num_local_nodes + 1),
num_local_nodes + 1,
dtype=numpy.int64
))
cell_connectivity.append(
numpy.c_[
num_local_nodes * numpy.ones(numcells, dtype=data.dtype),
data
].flatten()
)
len_array += len(cell_connectivity[-1])
cell_types = numpy.concatenate(cell_types)
cell_offsets = numpy.concatenate(cell_offsets)
cell_connectivity = numpy.concatenate(cell_connectivity)
connectivity = vtk.util.numpy_support.numpy_to_vtkIdTypeArray(
cell_connectivity.astype(numpy.int64),
deep=1
)
# wrap the data into a vtkCellArray
cell_array = vtk.vtkCellArray()
cell_array.SetCells(len(cell_types), connectivity)
# Add cell data to the mesh
mesh.SetCells(
numpy_support.numpy_to_vtk(
cell_types,
deep=1,
array_type=vtk.vtkUnsignedCharArray().GetDataType()
),
numpy_support.numpy_to_vtk(
cell_offsets,
deep=1,
array_type=vtk.vtkIdTypeArray().GetDataType()
),
cell_array
)
return mesh
0
Example 25
def toarray(self, target = None):
if target is None:
target = numpy.zeros((self.get_size(),), dtype=numpy.ubyte)
dtype = target.dtype
(entry, type_name, label, data) = self.record
target[:12] = self.header
if type_name=='SUBBLOCK':
if data is not None:
n = 12
for item in data:
item.toarray(target[n:])
n += item.get_size()
elif type_name == 'ASCII':
target[12:12+len(data)+1] = numpy.array([data+'\0']).view(dtype=dtype)
elif type_name == 'LONG':
target[12:12+4] = numpy.array([data], dtype=numpy.uint32).view(dtype=dtype)
elif type_name == 'DOUBLE':
target[12:12+8] = numpy.array([data], dtype=numpy.float64).view(dtype=dtype)
else:
raise NotImplementedError (repr(self.record))
return target
0
Example 26
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)
0
Example 27
Project: TileStache Source File: Composite.py
def _rgba2img(rgba):
""" Convert four Numeric array objects to PIL Image.
"""
assert type(rgba) is list
return Image.merge('RGBA', [_arr2img(numpy.round(band * 255.0).astype(numpy.ubyte)) for band in rgba])
0
Example 28
def make_label(text, filename, size=12, angle=0):
'''
Parameters:
-----------
text : string
Text to be displayed
filename : string
Path to a font
size : int
Font size in 1/64th points
angle : float
Text angle in degrees
'''
face = Face(filename)
face.set_char_size( size*64 )
angle = (angle/180.0)*math.pi
matrix = FT_Matrix( (int)( math.cos( angle ) * 0x10000 ),
(int)(-math.sin( angle ) * 0x10000 ),
(int)( math.sin( angle ) * 0x10000 ),
(int)( math.cos( angle ) * 0x10000 ))
flags = FT_LOAD_RENDER
pen = FT_Vector(0,0)
FT_Set_Transform( face._FT_Face, byref(matrix), byref(pen) )
previous = 0
xmin, xmax = 0, 0
ymin, ymax = 0, 0
for c in text:
face.load_char(c, flags)
kerning = face.get_kerning(previous, c)
previous = c
bitmap = face.glyph.bitmap
pitch = face.glyph.bitmap.pitch
width = face.glyph.bitmap.width
rows = face.glyph.bitmap.rows
top = face.glyph.bitmap_top
left = face.glyph.bitmap_left
pen.x += kerning.x
x0 = (pen.x >> 6) + left
x1 = x0 + width
y0 = (pen.y >> 6) - (rows - top)
y1 = y0 + rows
xmin, xmax = min(xmin, x0), max(xmax, x1)
ymin, ymax = min(ymin, y0), max(ymax, y1)
pen.x += face.glyph.advance.x
pen.y += face.glyph.advance.y
L = np.zeros((ymax-ymin, xmax-xmin),dtype=np.ubyte)
previous = 0
pen.x, pen.y = 0, 0
for c in text:
face.load_char(c, flags)
kerning = face.get_kerning(previous, c)
previous = c
bitmap = face.glyph.bitmap
pitch = face.glyph.bitmap.pitch
width = face.glyph.bitmap.width
rows = face.glyph.bitmap.rows
top = face.glyph.bitmap_top
left = face.glyph.bitmap_left
pen.x += kerning.x
x = (pen.x >> 6) - xmin + left
y = (pen.y >> 6) - ymin - (rows - top)
data = []
for j in range(rows):
data.extend(bitmap.buffer[j*pitch:j*pitch+width])
if len(data):
Z = np.array(data,dtype=np.ubyte).reshape(rows, width)
L[y:y+rows,x:x+width] |= Z[::-1,::1]
pen.x += face.glyph.advance.x
pen.y += face.glyph.advance.y
return L
0
Example 29
Project: glumpy Source File: font_manager.py
@property
def atlas_agg(self):
if FontManager._atlas_agg is None:
FontManager._atlas_agg = np.zeros((1024,1024,3),np.ubyte).view(Atlas)
return FontManager._atlas_agg
0
Example 30
Project: pyqtgraph Source File: GLViewWidget.py
def renderToArray(self, size, format=GL_BGRA, type=GL_UNSIGNED_BYTE, textureSize=1024, padding=256):
w,h = map(int, size)
self.makeCurrent()
tex = None
fb = None
try:
output = np.empty((w, h, 4), dtype=np.ubyte)
fb = glfbo.glGenFramebuffers(1)
glfbo.glBindFramebuffer(glfbo.GL_FRAMEBUFFER, fb )
glEnable(GL_TEXTURE_2D)
tex = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, tex)
texwidth = textureSize
data = np.zeros((texwidth,texwidth,4), dtype=np.ubyte)
## Test texture dimensions first
glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, texwidth, texwidth, 0, GL_RGBA, GL_UNSIGNED_BYTE, None)
if glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_WIDTH) == 0:
raise Exception("OpenGL failed to create 2D texture (%dx%d); too large for this hardware." % shape[:2])
## create teture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texwidth, texwidth, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.transpose((1,0,2)))
self.opts['viewport'] = (0, 0, w, h) # viewport is the complete image; this ensures that paintGL(region=...)
# is interpreted correctly.
p2 = 2 * padding
for x in range(-padding, w-padding, texwidth-p2):
for y in range(-padding, h-padding, texwidth-p2):
x2 = min(x+texwidth, w+padding)
y2 = min(y+texwidth, h+padding)
w2 = x2-x
h2 = y2-y
## render to texture
glfbo.glFramebufferTexture2D(glfbo.GL_FRAMEBUFFER, glfbo.GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0)
self.paintGL(region=(x, h-y-h2, w2, h2), viewport=(0, 0, w2, h2)) # only render sub-region
## read texture back to array
data = glGetTexImage(GL_TEXTURE_2D, 0, format, type)
data = np.fromstring(data, dtype=np.ubyte).reshape(texwidth,texwidth,4).transpose(1,0,2)[:, ::-1]
output[x+padding:x2-padding, y+padding:y2-padding] = data[padding:w2-padding, -(h2-padding):-padding]
finally:
self.opts['viewport'] = None
glfbo.glBindFramebuffer(glfbo.GL_FRAMEBUFFER, 0)
glBindTexture(GL_TEXTURE_2D, 0)
if tex is not None:
glDeleteTextures([tex])
if fb is not None:
glfbo.glDeleteFramebuffers([fb])
return output
0
Example 31
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]
0
Example 32
def render(self):
# Convert data to QImage for display.
profile = debug.Profiler()
if self.image is None or self.image.size == 0:
return
if isinstance(self.lut, collections.Callable):
lut = self.lut(self.image)
else:
lut = self.lut
if self.autoDownsample:
# reduce dimensions of image based on screen resolution
o = self.mapToDevice(QtCore.QPointF(0,0))
x = self.mapToDevice(QtCore.QPointF(1,0))
y = self.mapToDevice(QtCore.QPointF(0,1))
w = Point(x-o).length()
h = Point(y-o).length()
if w == 0 or h == 0:
self.qimage = None
return
xds = max(1, int(1.0 / w))
yds = max(1, int(1.0 / h))
axes = [1, 0] if self.axisOrder == 'row-major' else [0, 1]
image = fn.downsample(self.image, xds, axis=axes[0])
image = fn.downsample(image, yds, axis=axes[1])
self._lastDownsample = (xds, yds)
else:
image = self.image
# if the image data is a small int, then we can combine levels + lut
# into a single lut for better performance
levels = self.levels
if levels is not None and levels.ndim == 1 and image.dtype in (np.ubyte, np.uint16):
if self._effectiveLut is None:
eflsize = 2**(image.itemsize*8)
ind = np.arange(eflsize)
minlev, maxlev = levels
levdiff = maxlev - minlev
levdiff = 1 if levdiff == 0 else levdiff # don't allow division by 0
if lut is None:
efflut = fn.rescaleData(ind, scale=255./levdiff,
offset=minlev, dtype=np.ubyte)
else:
lutdtype = np.min_scalar_type(lut.shape[0]-1)
efflut = fn.rescaleData(ind, scale=(lut.shape[0]-1)/levdiff,
offset=minlev, dtype=lutdtype, clip=(0, lut.shape[0]-1))
efflut = lut[efflut]
self._effectiveLut = efflut
lut = self._effectiveLut
levels = None
# Assume images are in column-major order for backward compatibility
# (most images are in row-major order)
if self.axisOrder == 'col-major':
image = image.transpose((1, 0, 2)[:image.ndim])
argb, alpha = fn.makeARGB(image, lut=lut, levels=levels)
self.qimage = fn.makeQImage(argb, alpha, transpose=False)
0
Example 33
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))
0
Example 34
def toarray (self, target=None):
sz = self.get_size()
if target is None:
target = numpy.zeros((sz,), dtype=numpy.ubyte)
dtype = target.dtype
header = numpy.array([sz,len (self.colors), len (self.names), 0, 0, self.mono, 0,0,0,0], dtype=numpy.int32)
names = ''
for name in self.names:
names += '\x04\0\0\0' + name + '\x00'
noffset = sz - len(names)
names = numpy.array([names]).view (dtype=dtype)
colors = numpy.array (self.colors, dtype=numpy.uint8).ravel()
coffset = noffset - colors.nbytes
header[3] = coffset
header[4] = noffset
target[:header.nbytes] = header.view(dtype=dtype)
target[coffset:coffset + colors.nbytes] = colors
target[noffset:noffset + names.nbytes] = names
return target
0
Example 35
def make_pil_image(*args, **kwargs):
'''Creates a PIL Image object.
USAGE: make_pil_image(source [, bands] [stretch=True] [stretch_all=False],
[bounds = (lower, upper)] )
See `get_rgb` for description of arguments.
'''
import numpy
import io
try:
from PIL import Image, ImageDraw
except ImportError:
import Image
import ImageDraw
rgb = get_rgb(*args, **kwargs)
rgb = (rgb * 255).astype(numpy.ubyte)
im = Image.fromarray(rgb)
return im
0
Example 36
Project: pyqtgraph Source File: GradientEditorItem.py
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
0
Example 37
Project: TileStache Source File: Composite.py
def _img2arr(im):
""" Convert PIL Image to Numeric array.
"""
assert im.mode == 'L'
return numpy.reshape(numpy.fromstring(im.tobytes(), numpy.ubyte), (im.size[1], im.size[0]))
0
Example 38
def render(filename = "Vera.ttf", hinting = (False,False), gamma = 1.5, lcd=False):
text = "A Quick Brown Fox Jumps Over The Lazy Dog 0123456789"
W,H,D = 680, 280, 1
Z = np.zeros( (H,W), dtype=np.ubyte )
face = Face(filename)
pen = Vector(5*64, (H-10)*64)
flags = FT_LOAD_RENDER
if hinting[1]: flags |= FT_LOAD_FORCE_AUTOHINT
else: flags |= FT_LOAD_NO_HINTING
if hinting[0]: hres, hscale = 72, 1.0
else: hres, hscale = 72*10, 0.1
if lcd:
flags |= FT_LOAD_TARGET_LCD
Z = np.zeros( (H,W,3), dtype=np.ubyte )
set_lcd_filter( FT_LCD_FILTER_DEFAULT )
for size in range(9,23):
face.set_char_size( size * 64, 0, hres, 72 )
matrix = Matrix( int((hscale) * 0x10000), int((0.0) * 0x10000),
int((0.0) * 0x10000), int((1.0) * 0x10000) )
previous = 0
pen.x = 5*64
for current in text:
face.set_transform( matrix, pen )
face.load_char( current, flags)
kerning = face.get_kerning( previous, current, FT_KERNING_UNSCALED )
pen.x += kerning.x
glyph = face.glyph
bitmap = glyph.bitmap
x, y = glyph.bitmap_left, glyph.bitmap_top
w, h, p = bitmap.width, bitmap.rows, bitmap.pitch
buff = np.array(bitmap.buffer, dtype=np.ubyte).reshape((h,p))
if lcd:
Z[H-y:H-y+h,x:x+w/3].flat |= buff[:,:w].flatten()
else:
Z[H-y:H-y+h,x:x+w].flat |= buff[:,:w].flatten()
pen.x += glyph.advance.x
previous = current
pen.y -= (size+4)*64
# Gamma correction
Z = (Z/255.0)**(gamma)
Z = ((1-Z)*255).astype(np.ubyte)
if lcd:
I = Image.fromarray(Z, mode='RGB')
else:
I = Image.fromarray(Z, mode='L')
name = filename.split('.')[0]
filename = '%s-gamma(%.1f)-hinting(%d,%d)-lcd(%d).png' % (name,gamma,hinting[0],hinting[1],lcd)
I.save(filename)
0
Example 39
def _save_failed_test(data, expect, filename):
from ..io import _make_png
commit, error = run_subprocess(['git', 'rev-parse', 'HEAD'])
name = filename.split('/')
name.insert(-1, commit.strip())
filename = '/'.join(name)
host = 'data.vispy.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 = make_diff_image(data, expect)
img[2:2+diff.shape[0], -diff.shape[1]-2:-2] = diff
png = _make_png(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)
0
Example 40
def buildAtlas(self):
# get rendered array for all symbols, keep track of avg/max width
rendered = {}
avgWidth = 0.0
maxWidth = 0
images = []
for key, sourceRect in self.symbolMap.items():
if sourceRect.width() == 0:
img = renderSymbol(key[0], key[1], sourceRect.pen, sourceRect.brush)
images.append(img) ## we only need this to prevent the images being garbage collected immediately
arr = fn.imageToArray(img, copy=False, transpose=False)
else:
(y,x,h,w) = sourceRect.getRect()
arr = self.atlasData[int(x):int(x+w), int(y):int(y+w)]
rendered[key] = arr
w = arr.shape[0]
avgWidth += w
maxWidth = max(maxWidth, w)
nSymbols = len(rendered)
if nSymbols > 0:
avgWidth /= nSymbols
width = max(maxWidth, avgWidth * (nSymbols**0.5))
else:
avgWidth = 0
width = 0
# sort symbols by height
symbols = sorted(rendered.keys(), key=lambda x: rendered[x].shape[1], reverse=True)
self.atlasRows = []
x = width
y = 0
rowheight = 0
for key in symbols:
arr = rendered[key]
w,h = arr.shape[:2]
if x+w > width:
y += rowheight
x = 0
rowheight = h
self.atlasRows.append([y, rowheight, 0])
self.symbolMap[key].setRect(y, x, h, w)
x += w
self.atlasRows[-1][2] = x
height = y + rowheight
self.atlasData = np.zeros((int(width), int(height), 4), dtype=np.ubyte)
for key in symbols:
y, x, h, w = self.symbolMap[key].getRect()
self.atlasData[int(x):int(x+w), int(y):int(y+h)] = rendered[key]
self.atlas = None
self.atlasValid = True
self.max_width = maxWidth
0
Example 41
Project: freetype-py Source File: opengl.py
def makefont(filename, size):
global texid
# Load font and check it is monotype
face = Face(filename)
face.set_char_size( size*64 )
if not face.is_fixed_width:
raise 'Font is not monotype'
# Determine largest glyph size
width, height, ascender, descender = 0, 0, 0, 0
for c in range(32,128):
face.load_char( chr(c), FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT )
bitmap = face.glyph.bitmap
width = max( width, bitmap.width )
ascender = max( ascender, face.glyph.bitmap_top )
descender = max( descender, bitmap.rows-face.glyph.bitmap_top )
height = ascender+descender
# Generate texture data
Z = numpy.zeros((height*6, width*16), dtype=numpy.ubyte)
for j in range(6):
for i in range(16):
face.load_char(chr(32+j*16+i), FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT )
bitmap = face.glyph.bitmap
x = i*width + face.glyph.bitmap_left
y = j*height + ascender - face.glyph.bitmap_top
Z[y:y+bitmap.rows,x:x+bitmap.width].flat = bitmap.buffer
# Bound texture
texid = gl.glGenTextures(1)
gl.glBindTexture( gl.GL_TEXTURE_2D, texid )
gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR )
gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR )
gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, gl.GL_ALPHA, Z.shape[1], Z.shape[0], 0,
gl.GL_ALPHA, gl.GL_UNSIGNED_BYTE, Z )
# Generate display lists
dx, dy = width/float(Z.shape[1]), height/float(Z.shape[0])
base = gl.glGenLists(8*16)
for i in range(8*16):
c = chr(i)
x = i%16
y = i//16-2
gl.glNewList(base+i, gl.GL_COMPILE)
if (c == '\n'):
gl.glPopMatrix( )
gl.glTranslatef( 0, -height, 0 )
gl.glPushMatrix( )
elif (c == '\t'):
gl.glTranslatef( 4*width, 0, 0 )
elif (i >= 32):
gl.glBegin( gl.GL_QUADS )
gl.glTexCoord2f( (x )*dx, (y+1)*dy ), gl.glVertex( 0, -height )
gl.glTexCoord2f( (x )*dx, (y )*dy ), gl.glVertex( 0, 0 )
gl.glTexCoord2f( (x+1)*dx, (y )*dy ), gl.glVertex( width, 0 )
gl.glTexCoord2f( (x+1)*dx, (y+1)*dy ), gl.glVertex( width, -height )
gl.glEnd( )
gl.glTranslatef( width, 0, 0 )
gl.glEndList( )
0
Example 42
def test(self, im1, im2, message):
self.show()
self.console.write('------------------')
self.console.write(message)
if im2 is None:
self.console.write('Image1: %s %s Image2: [no standard]' %
(im1.shape, im1.dtype))
im2 = np.zeros((1, 1, 3), dtype=np.ubyte)
else:
self.console.write('Image1: %s %s Image2: %s %s' %
(im1.shape, im1.dtype, im2.shape, im2.dtype))
self.console.write('(P)ass or (F)ail this test?')
self.views[0].image.set_data(im1)
self.views[1].image.set_data(im2)
diff = make_diff_image(im1, im2)
self.views[2].image.set_data(diff)
self.views[0].camera.set_range()
while True:
self.app.process_events()
if self.last_key is None:
pass
elif self.last_key.lower() == 'p':
self.console.write('PASS')
break
elif self.last_key.lower() in ('f', 'esc'):
self.console.write('FAIL')
raise Exception("User rejected test result.")
time.sleep(0.03)
for v in self.views:
v.image.set_data(np.zeros((1, 1, 3), dtype=np.ubyte))
0
Example 43
def setup(self):
for i in range(0,self.numofchu):
# create freetype bitmap
txt = self.text[i]
dataAlpha = self.make_bitmap(txt)
temp = np.ones( (dataAlpha.shape[0], dataAlpha.shape[1], 4), dtype = np.ubyte)
temp [:,:,0] *= int(255 * self.fontcolor[i][0])
temp[:,:,1] *= int(255 * self.fontcolor[i][1])
temp[:,:,2] *= int(255 * self.fontcolor[i][2])
temp[:,:,3] = dataAlpha
self.data.append(temp)
t = dataAlpha.shape
self.height[i] = t[0]/64. #(96,64) - (w,h) is the size of one character in the normal Vera font
self.width[i] = t[1]/90#96.
# create 2d texture
self.data_ptr.append( self.data[i].ctypes.data)
self.tex_ptr.append(GLuint(0))
glGenTextures(1, self.tex_ptr[i])
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glBindTexture(GL_TEXTURE_2D, self.tex_ptr[i])
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.data[i].shape[1],
self.data[i].shape[0], 0, GL_RGBA,
GL_UNSIGNED_BYTE, self.data_ptr[i])
glBindTexture(GL_TEXTURE_2D, 0)
0
Example 44
def __init__(self, width=1024, height=1024, depth=1):
'''
Initialize a new atlas of given size.
Parameters
----------
width : int
Width of the underlying texture
height : int
Height of the underlying texture
depth : 1 or 3
Depth of the underlying texture
'''
self.width = int(math.pow(2, int(math.log(width, 2) + 0.5)))
self.height = int(math.pow(2, int(math.log(height, 2) + 0.5)))
self.depth = depth
self.nodes = [ (0,0,self.width), ]
self.data = np.zeros((self.height, self.width, self.depth),
dtype=np.ubyte)
self.texid = 0
self.used = 0
0
Example 45
def make_bitmap(self, text):
""" create a bit map of a text
Parameters
----------
text : str
Returns
-------
bitmap : array, shape (height, width)
"""
face = Face(get_font( 'Vera' ))
face.set_char_size(96 * 64) #48*64 )
slot = face.glyph
# First pass to compute bbox
width, height, baseline = 0, 0, 0
previous = 0
for i,c in enumerate(text):
face.load_char(c)
bitmap = slot.bitmap
height = max(height, bitmap.rows + max(0,-(slot.bitmap_top-bitmap.rows))) + 1
baseline = max(baseline, max(0, - (slot.bitmap_top - bitmap.rows)))
kerning = face.get_kerning(previous, c)
width += (slot.advance.x >> 6) + (kerning.x >> 6)
previous = c
Z = np.zeros((height,width), dtype=np.ubyte)
# Second pass for actual rendering
x, y = 0, 0
previous = 0
for c in text:
face.load_char(c)
bitmap = slot.bitmap
top = slot.bitmap_top
left = slot.bitmap_left
w,h = bitmap.width, bitmap.rows
y = height-baseline-top
kerning = face.get_kerning(previous, c)
x += (kerning.x >> 6)
Z[y:y+h,x:x+w] |= np.array(bitmap.buffer).reshape(h,w)
x += (slot.advance.x >> 6) # for the last one, use bitmap.width
previous = c
return Z
0
Example 46
def __init__(self, name, location, text, width, height, targetpoint = None, linewidth = 3.0, \
fontcolor = (1,1,1), pointercolor = (1,1,1)):
""" A Text3D actor
"""
super(Text3D, self).__init__(name)
self.vertices = location
self.width = width
self.height = height
self.text = text
self.targetpoint = targetpoint
self.linewidth = linewidth
self.fontcolor = fontcolor
self.pointercolor = pointercolor
# create freetype bitmap
dataAlpha = self.make_bitmap(self.text)
self.data = np.ones( (dataAlpha.shape[0], dataAlpha.shape[1], 4), dtype = np.ubyte)
self.data[:,:,0] *= int(255 * self.fontcolor[0])
self.data[:,:,1] *= int(255 * self.fontcolor[1])
self.data[:,:,2] *= int(255 * self.fontcolor[2])
self.data[:,:,3] = dataAlpha
# create 2d texture
self.data_ptr = self.data.ctypes.data
self.tex_ptr = GLuint(0)
glGenTextures(1, self.tex_ptr)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glBindTexture(GL_TEXTURE_2D, self.tex_ptr)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.data.shape[1],
self.data.shape[0], 0, GL_RGBA,
GL_UNSIGNED_BYTE, self.data_ptr)
glBindTexture(GL_TEXTURE_2D, 0)
0
Example 47
def export(self, fileName=None, toBytes=False, copy=False):
if fileName is None and not toBytes and not copy:
if USE_PYSIDE:
filter = ["*."+str(f) for f in QtGui.QImageWriter.supportedImageFormats()]
else:
filter = ["*."+bytes(f).decode('utf-8') for f in QtGui.QImageWriter.supportedImageFormats()]
preferred = ['*.png', '*.tif', '*.jpg']
for p in preferred[::-1]:
if p in filter:
filter.remove(p)
filter.insert(0, p)
self.fileSaveDialog(filter=filter)
return
targetRect = QtCore.QRect(0, 0, self.params['width'], self.params['height'])
sourceRect = self.getSourceRect()
#self.png = QtGui.QImage(targetRect.size(), QtGui.QImage.Format_ARGB32)
#self.png.fill(pyqtgraph.mkColor(self.params['background']))
w, h = self.params['width'], self.params['height']
if w == 0 or h == 0:
raise Exception("Cannot export image with size=0 (requested export size is %dx%d)" % (w,h))
bg = np.empty((self.params['width'], self.params['height'], 4), dtype=np.ubyte)
color = self.params['background']
bg[:,:,0] = color.blue()
bg[:,:,1] = color.green()
bg[:,:,2] = color.red()
bg[:,:,3] = color.alpha()
self.png = fn.makeQImage(bg, alpha=True)
## set resolution of image:
origTargetRect = self.getTargetRect()
resolutionScale = targetRect.width() / origTargetRect.width()
#self.png.setDotsPerMeterX(self.png.dotsPerMeterX() * resolutionScale)
#self.png.setDotsPerMeterY(self.png.dotsPerMeterY() * resolutionScale)
painter = QtGui.QPainter(self.png)
#dtr = painter.deviceTransform()
try:
self.setExportMode(True, {'antialias': self.params['antialias'], 'background': self.params['background'], 'painter': painter, 'resolutionScale': resolutionScale})
painter.setRenderHint(QtGui.QPainter.Antialiasing, self.params['antialias'])
self.getScene().render(painter, QtCore.QRectF(targetRect), QtCore.QRectF(sourceRect))
finally:
self.setExportMode(False)
painter.end()
if copy:
QtGui.QApplication.clipboard().setImage(self.png)
elif toBytes:
return self.png
else:
self.png.save(fileName)
0
Example 48
Project: pyqtgraph Source File: GLViewWidget.py
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
0
Example 49
def load(self, charcodes = ''):
'''
Build glyphs corresponding to individual characters in charcodes.
Parameters:
-----------
charcodes: [str | unicode]
Set of characters to be represented
'''
face = Face( self.filename )
pen = Vector(0,0)
hres = 16*72
hscale = 1.0/16
for charcode in charcodes:
face.set_char_size( int(self.size * 64), 0, hres, 72 )
matrix = Matrix( int((hscale) * 0x10000), int((0.0) * 0x10000),
int((0.0) * 0x10000), int((1.0) * 0x10000) )
face.set_transform( matrix, pen )
if charcode in self.glyphs.keys():
continue
self.dirty = True
flags = FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT
flags |= FT_LOAD_TARGET_LCD
face.load_char( charcode, flags )
bitmap = face.glyph.bitmap
left = face.glyph.bitmap_left
top = face.glyph.bitmap_top
width = face.glyph.bitmap.width
rows = face.glyph.bitmap.rows
pitch = face.glyph.bitmap.pitch
x,y,w,h = self.atlas.get_region(width/self.depth+2, rows+2)
if x < 0:
print ('Missed !')
continue
x,y = x+1, y+1
w,h = w-2, h-2
data = []
for i in range(rows):
data.extend(bitmap.buffer[i*pitch:i*pitch+width])
data = np.array(data,dtype=np.ubyte).reshape(h,w,3)
gamma = 1.5
Z = ((data/255.0)**(gamma))
data = (Z*255).astype(np.ubyte)
self.atlas.set_region((x,y,w,h), data)
# Build glyph
size = w,h
offset = left, top
advance= face.glyph.advance.x, face.glyph.advance.y
u0 = (x + 0.0)/float(self.atlas.width)
v0 = (y + 0.0)/float(self.atlas.height)
u1 = (x + w - 0.0)/float(self.atlas.width)
v1 = (y + h - 0.0)/float(self.atlas.height)
texcoords = (u0,v0,u1,v1)
glyph = TextureGlyph(charcode, size, offset, advance, texcoords)
self.glyphs[charcode] = glyph
# Generate kerning
for g in self.glyphs.values():
# 64 * 64 because of 26.6 encoding AND the transform matrix used
# in texture_font_load_face (hres = 64)
kerning = face.get_kerning(g.charcode, charcode, mode=FT_KERNING_UNFITTED)
if kerning.x != 0:
glyph.kerning[g.charcode] = kerning.x/(64.0*64.0)
kerning = face.get_kerning(charcode, g.charcode, mode=FT_KERNING_UNFITTED)
if kerning.x != 0:
g.kerning[charcode] = kerning.x/(64.0*64.0)
0
Example 50
def make_bitmap(self, text):
face = Face(get_font( 'Vera' ))
face.set_char_size( 96*64 ) #48*64 )
slot = face.glyph
# First pass to compute bbox
width, height, baseline = 0, 0, 0
previous = 0
for i,c in enumerate(text):
face.load_char(c)
bitmap = slot.bitmap
height = max(height,
bitmap.rows + max(0,-(slot.bitmap_top-bitmap.rows)))
baseline = max(baseline, max(0,-(slot.bitmap_top-bitmap.rows)))
kerning = face.get_kerning(previous, c)
width += (slot.advance.x >> 6) + (kerning.x >> 6)
previous = c
Z = np.zeros((height,width), dtype=np.ubyte)
# Second pass for actual rendering
x, y = 0, 0
previous = 0
for c in text:
face.load_char(c)
bitmap = slot.bitmap
top = slot.bitmap_top
left = slot.bitmap_left
w,h = bitmap.width, bitmap.rows
y = height-baseline-top
kerning = face.get_kerning(previous, c)
x += (kerning.x >> 6)
Z[y:y+h,x:x+w] |= np.array(bitmap.buffer).reshape(h,w)
x += (slot.advance.x >> 6) # for the last one, use bitmap.width
previous = c
return Z