def colormap_lut(color = 'viridis', ncolors = None):
# build lookup table
if color == 'r':
pos = np.array([0.0, 1.0])
color = np.array([[0,0,0,255], [255,0,0,255]], dtype=np.ubyte)
ncolors = 512;
elif color =='g':
pos = np.array([0.0, 1.0])
color = np.array([[0,0,0,255], [0,255,0,255]], dtype=np.ubyte)
ncolors = 512;
elif color =='b':
pos = np.array([0.0, 1.0])
color = np.array([[0,0,0,255], [0,0,255,255]], dtype=np.ubyte)
ncolors = 512;
else:
#pos = np.array([0.0, 0.25, 0.5, 0.75, 1.0])
#color = np.array([[0,0,255,255], [0,255,255,255], [0,255,0,255], [255,255,0,255], [255,0,0,255]], dtype=np.ubyte)
#color = np.array([[0,0,128,255], [0,255,255,255], [0,255,0,255], [255,255,0,255], [128,0,0,255]], dtype=np.ubyte)
cmap = cm.get_cmap(color);
if ncolors is None:
ncolors = cmap.N;
pos = np.linspace(0.0, 1.0, ncolors);
color = cmap(pos, bytes = True);
cmap = pg.ColorMap(pos, color)
return cmap.getLookupTable(0.0, 1.0, ncolors);
python类ubyte()的实例源码
def colormap_lut(color = 'viridis', ncolors = None):
# build lookup table
if color == 'r':
pos = np.array([0.0, 1.0])
color = np.array([[0,0,0,255], [255,0,0,255]], dtype=np.ubyte)
ncolors = 512;
elif color =='g':
pos = np.array([0.0, 1.0])
color = np.array([[0,0,0,255], [0,255,0,255]], dtype=np.ubyte)
ncolors = 512;
elif color =='b':
pos = np.array([0.0, 1.0])
color = np.array([[0,0,0,255], [0,0,255,255]], dtype=np.ubyte)
ncolors = 512;
else:
#pos = np.array([0.0, 0.25, 0.5, 0.75, 1.0])
#color = np.array([[0,0,255,255], [0,255,255,255], [0,255,0,255], [255,255,0,255], [255,0,0,255]], dtype=np.ubyte)
#color = np.array([[0,0,128,255], [0,255,255,255], [0,255,0,255], [255,255,0,255], [128,0,0,255]], dtype=np.ubyte)
cmap = cm.get_cmap(color);
if ncolors is None:
ncolors = cmap.N;
pos = np.linspace(0.0, 1.0, ncolors);
color = cmap(pos, bytes = True);
cmap = pg.ColorMap(pos, color)
return cmap.getLookupTable(0.0, 1.0, ncolors);
def adjust_contrast(image, contrast):
if (contrast < 0):
contrast = 0
elif (contrast > 200):
contrast = 200
contrast = contrast / 100
img = image.astype(np.float) * contrast
img[img > 255] = 255
img[img < 0] = 0
return img.astype(np.ubyte)
def adjust_brightness(image, brightness):
if (brightness < 0):
brightness = 0
elif (brightness > 200):
brightness = 200
brightness = (((brightness) * (510)) / 200) - 255
img = image.astype(np.float) + brightness
img[img > 255] = 255
img[img < 0] = 0
return img.astype(np.ubyte)
def kmeans(X, n_clusters, **kwargs):
"""Classify vectors in X using K-Means algorithm with n_clusters.
Arguments in kwargs are passed to scikit-learn MiniBatchKMeans.
Returns a tuple of cluster centers and predicted labels."""
clf = MiniBatchKMeans(n_clusters=n_clusters, **kwargs)
labels = clf.fit_predict(X)
centers = clf.cluster_centers_.astype(np.ubyte)
return centers, labels
def get_mask_polygons(polygons, height, width):
"""Turn a list of polygons into a mask image of height by width.
Each polygon is expressed as a list of [x, y] points."""
mask = np.zeros((height, width), dtype=np.ubyte)
cv2.fillPoly(mask, np.int32(polygons), color=255)
return mask
def convert(image):
"""Convert a scikit-image binary image matrix to OpenCV"""
with warnings.catch_warnings(record=True):
warnings.filterwarnings('ignore', category=DataConversionWarning)
return minmax_scale(image, (0, 255)).astype(np.ubyte)
def getpgcmap(cmp='BuRd'):
import pyqtgraph as pg
import numpy as np
if cmp =='bryw':
STEPS = np.array([0.0, 0.2, 0.6, 1.0])
CLRS = ['k', 'r', 'y', 'w']
## Create a ColorMap
clrmp = pg.ColorMap(STEPS, np.array([pg.colorTuple(pg.Color(c)) for c in CLRS]))
## Get the LookupTable
lut = clrmp.getLookupTable()
elif cmp == 'TrmBlk':
pos = np.array([0.0, 0.5, 1.0])
color = np.array([[0,0,0,255], [255,128,0,255], [255,255,0,255]], dtype=np.ubyte)
map = pg.ColorMap(pos, color)
lut = map.getLookupTable(0.0, 1.0, 256)
elif cmp == 'RdBu':
pos = np.array([0.0,0.5,1.0])
color = np.array([[255,0,0,0],[255,255,255,255],[0,0,255,0]],dtype=np.ubyte)
map = pg.ColorMap(pos,color)
lut = map.getLookupTable(0.0,1.0,256)
elif cmp == 'BuRd':
pos = np.array([0.0,0.5,1.0])
color = np.array([[0,0,255,0],[255,255,255,255],[255,0,0,0]],dtype=np.ubyte)
map = pg.ColorMap(pos,color)
lut = map.getLookupTable(0.0,1.0,256)
return lut
def get_mnist_images():
import gzip
from tensorflow.contrib.learn.python.learn.datasets import base
import numpy
def extract_images(f):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth].
Args:
f: A file object that can be passed into a gzip reader.
Returns:
data: A 4D uint8 numpy array [index, y, x, depth].
Raises:
ValueError: If the bytestream does not start with 2051.
"""
print('Extracting', f.name)
with gzip.GzipFile(fileobj=f) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
raise ValueError('Invalid magic number %d in MNIST image file: %s' %
(magic, f.name))
num_images = _read32(bytestream)
rows = _read32(bytestream)
cols = _read32(bytestream)
buf = bytestream.read(rows * cols * num_images)
data = numpy.frombuffer(buf, dtype=numpy.uint8)
data = data.reshape(num_images, rows, cols, 1)
return data
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
source_url = 'https://storage.googleapis.com/cvdf-datasets/mnist/'
local_file = base.maybe_download(TRAIN_IMAGES, '/tmp',
source_url + TRAIN_IMAGES)
train_images = extract_images(open(local_file, 'rb'))
train_images = train_images.reshape(60000, 28**2).T.astype(np.float64)/255
return train_images
# helper utilities
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
def calculate_numpy_brga_for(name: str) -> np.ndarray:
colormap = maps.get(name, maps[default_colormap])
result = np.zeros((len(colormap), 4), dtype=np.ubyte)
for i, color in enumerate(colormap):
result[i] = (int(255 * color[2]), int(255 * color[1]), int(255 * color[0]), 255)
return result
def amean (inarray,dimension=None,keepdims=0):
"""
Calculates the arithmatic mean of the values in the passed array.
That is: 1/n * (x1 + x2 + ... + xn). Defaults to ALL values in the
passed array. Use dimension=None to flatten array first. REMEMBER: if
dimension=0, it collapses over dimension 0 ('rows' in a 2D array) only, and
if dimension is a sequence, it collapses over all specified dimensions. If
keepdims is set to 1, the resulting array will have as many dimensions as
inarray, with only 1 'level' per dim that was collapsed over.
Usage: amean(inarray,dimension=None,keepdims=0)
Returns: arithematic mean calculated over dim(s) in dimension
"""
if inarray.dtype in [N.int_, N.short,N.ubyte]:
inarray = inarray.astype(N.float_)
if dimension == None:
inarray = N.ravel(inarray)
sum = N.add.reduce(inarray)
denom = float(len(inarray))
elif type(dimension) in [IntType,FloatType]:
sum = asum(inarray,dimension)
denom = float(inarray.shape[dimension])
if keepdims == 1:
shp = list(inarray.shape)
shp[dimension] = 1
sum = N.reshape(sum,shp)
else: # must be a TUPLE of dims to average over
dims = list(dimension)
dims.sort()
dims.reverse()
sum = inarray *1.0
for dim in dims:
sum = N.add.reduce(sum,dim)
denom = N.array(N.multiply.reduce(N.take(inarray.shape,dims)),N.float_)
if keepdims == 1:
shp = list(inarray.shape)
for dim in dims:
shp[dim] = 1
sum = N.reshape(sum,shp)
return sum/denom
def atmean(a,limits=None,inclusive=(1,1)):
"""
Returns the arithmetic mean of all values in an array, ignoring values
strictly outside the sequence passed to 'limits'. Note: either limit
in the sequence, or the value of limits itself, can be set to None. The
inclusive list/tuple determines whether the lower and upper limiting bounds
(respectively) are open/exclusive (0) or closed/inclusive (1).
Usage: atmean(a,limits=None,inclusive=(1,1))
"""
if a.dtype in [N.int_, N.short,N.ubyte]:
a = a.astype(N.float_)
if limits == None:
return mean(a)
assert type(limits) in [ListType,TupleType,N.ndarray], "Wrong type for limits in atmean"
if inclusive[0]: lowerfcn = N.greater_equal
else: lowerfcn = N.greater
if inclusive[1]: upperfcn = N.less_equal
else: upperfcn = N.less
if limits[0] > N.maximum.reduce(N.ravel(a)) or limits[1] < N.minimum.reduce(N.ravel(a)):
raise ValueError, "No array values within given limits (atmean)."
elif limits[0]==None and limits[1]<>None:
mask = upperfcn(a,limits[1])
elif limits[0]<>None and limits[1]==None:
mask = lowerfcn(a,limits[0])
elif limits[0]<>None and limits[1]<>None:
mask = lowerfcn(a,limits[0])*upperfcn(a,limits[1])
s = float(N.add.reduce(N.ravel(a*mask)))
n = float(N.add.reduce(N.ravel(mask)))
return s/n
def asum (a, dimension=None,keepdims=0):
"""
An alternative to the Numeric.add.reduce function, which allows one to
(1) collapse over multiple dimensions at once, and/or (2) to retain
all dimensions in the original array (squashing one down to size.
Dimension can equal None (ravel array first), an integer (the
dimension over which to operate), or a sequence (operate over multiple
dimensions). If keepdims=1, the resulting array will have as many
dimensions as the input array.
Usage: asum(a, dimension=None, keepdims=0)
Returns: array summed along 'dimension'(s), same _number_ of dims if keepdims=1
"""
if type(a) == N.ndarray and a.dtype in [N.int_, N.short, N.ubyte]:
a = a.astype(N.float_)
if dimension == None:
s = N.sum(N.ravel(a))
elif type(dimension) in [IntType,FloatType]:
s = N.add.reduce(a, dimension)
if keepdims == 1:
shp = list(a.shape)
shp[dimension] = 1
s = N.reshape(s,shp)
else: # must be a SEQUENCE of dims to sum over
dims = list(dimension)
dims.sort()
dims.reverse()
s = a *1.0
for dim in dims:
s = N.add.reduce(s,dim)
if keepdims == 1:
shp = list(a.shape)
for dim in dims:
shp[dim] = 1
s = N.reshape(s,shp)
return s
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)
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
def map(self, data, mode='byte'):
"""
Return an array of colors corresponding to *data*.
============== =================================================================
**Arguments:**
data A numpy record array where the fields in data.dtype match those
defined by a prior call to setFields().
mode Either 'byte' or 'float'. For 'byte', the method returns an array
of dtype ubyte with values scaled 0-255. For 'float', colors are
returned as 0.0-1.0 float values.
============== =================================================================
"""
if isinstance(data, dict):
data = np.array([tuple(data.values())], dtype=[(k, float) for k in data.keys()])
colors = np.zeros((len(data),4))
for item in self.children():
if not item['Enabled']:
continue
chans = item.param('Channels..')
mask = np.empty((len(data), 4), dtype=bool)
for i,f in enumerate(['Red', 'Green', 'Blue', 'Alpha']):
mask[:,i] = chans[f]
colors2 = item.map(data)
op = item['Operation']
if op == 'Add':
colors[mask] = colors[mask] + colors2[mask]
elif op == 'Multiply':
colors[mask] *= colors2[mask]
elif op == 'Overlay':
a = colors2[:,3:4]
c3 = colors * (1-a) + colors2 * a
c3[:,3:4] = colors[:,3:4] + (1-colors[:,3:4]) * a
colors = c3
elif op == 'Set':
colors[mask] = colors2[mask]
colors = np.clip(colors, 0, 1)
if mode == 'byte':
colors = (colors * 255).astype(np.ubyte)
return colors
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)
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)