text stringlengths 81 112k |
|---|
point mutation, addition, removal
def mutate(self,p_i,func_set,term_set): #, max_depth=2
"""point mutation, addition, removal"""
self.point_mutate(p_i,func_set,term_set) |
point mutation on individual p_i
def point_mutate(self,p_i,func_set,term_set):
"""point mutation on individual p_i"""
# point mutation
x = self.random_state.randint(len(p_i))
arity = p_i[x].arity[p_i[x].in_type]
# find eligible replacements based on arity and type
reps =... |
checks whether program p makes a syntactically valid tree.
checks that the accumulated program length is always greater than the
accumulated arities, indicating that the appropriate number of arguments is
alway present for functions. It then checks that the sum of arties +1
exactly equa... |
run utility function for MDR nodes.
def run_MDR(n,stack_float,labels=None):
"""run utility function for MDR nodes."""
# need to check that tmp is categorical
x1 = stack_float.pop()
x2 = stack_float.pop()
# check data is categorical
if len(np.unique(x1))<=3 and len(np.unique(x2))<=3:
tm... |
returns equation string for program stack
def stack_2_eqn(self,p):
"""returns equation string for program stack"""
stack_eqn = []
if p: # if stack is not empty
for n in p.stack:
self.eval_eqn(n,stack_eqn)
return stack_eqn[-1]
return [] |
returns equation strings from stacks
def stacks_2_eqns(self,stacks):
"""returns equation strings from stacks"""
if stacks:
return list(map(lambda p: self.stack_2_eqn(p), stacks))
else:
return [] |
makes a program stack
def make_program(self,stack,func_set,term_set,max_d,ntype):
"""makes a program stack"""
# print("stack:",stack,"max d:",max_d)
if max_d == 0:
ts = [t for t in term_set if t.out_type==ntype]
if not ts:
raise ValueError('no ts. ntype:... |
initializes population of features as GP stacks.
def init_pop(self):
"""initializes population of features as GP stacks."""
pop = Pop(self.population_size)
seed_with_raw_features = False
# make programs
if self.seed_with_ml:
# initial population is the components of ... |
Main function that is called when FEW is run on the command line
def main():
"""Main function that is called when FEW is run on the command line"""
parser = argparse.ArgumentParser(description='A feature engineering wrapper'
' for machine learning algorithms.',
... |
Fit model to data
def fit(self, features, labels):
"""Fit model to data"""
# setup data
# imputation
if self.clean:
features = self.impute_data(features)
# save the number of features
self.n_features = features.shape[1]
self.n_samples = features.shap... |
return a transformation of x using population outputs
def transform(self,x,inds=None,labels = None):
"""return a transformation of x using population outputs"""
if inds:
# return np.asarray(Parallel(n_jobs=10)(delayed(self.out)(I,x,labels,self.otype)
# ... |
Imputes data set containing Nan values
def impute_data(self,x):
"""Imputes data set containing Nan values"""
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
return imp.fit_transform(x) |
remove nan and inf rows from x
def clean(self,x):
"""remove nan and inf rows from x"""
return x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] |
set nan and inf rows from x to zero
def clean_with_zeros(self,x):
""" set nan and inf rows from x to zero"""
x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] = 0
return x |
predict on a holdout data set.
def predict(self, testing_features):
"""predict on a holdout data set."""
# print("best_inds:",self._best_inds)
# print("best estimator size:",self._best_estimator.coef_.shape)
if self.clean:
testing_features = self.impute_data(testing_features... |
Convenience function that fits a pipeline then predicts on the
provided features
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
labels: array-like {n_samples}
List of class labels for prediction
Returns
... |
estimates accuracy on testing set
def score(self, testing_features, testing_labels):
"""estimates accuracy on testing set"""
# print("test features shape:",testing_features.shape)
# print("testing labels shape:",testing_labels.shape)
yhat = self.predict(testing_features)
return ... |
exports engineered features
Parameters
----------
output_file_name: string
String containing the path and file name of the desired output file
Returns
-------
None
def export(self, output_file_name):
"""exports engineered features
Parameter... |
prints model contained in best inds, if ml has a coefficient property.
otherwise, prints the features generated by FEW.
def print_model(self,sep='\n'):
"""prints model contained in best inds, if ml has a coefficient property.
otherwise, prints the features generated by FEW."""
model = '... |
returns the indices of individuals with valid fitness.
def valid_loc(self,F=None):
"""returns the indices of individuals with valid fitness."""
if F is not None:
return [i for i,f in enumerate(F) if np.all(f < self.max_fit) and np.all(f >= 0)]
else:
return [i for i,f in ... |
returns the sublist of individuals with valid fitness.
def valid(self,individuals=None,F=None):
"""returns the sublist of individuals with valid fitness."""
if F:
valid_locs = self.valid_loc(F)
else:
valid_locs = self.valid_loc(self.F)
if individuals:
... |
compute mean diversity of individual outputs
def get_diversity(self,X):
"""compute mean diversity of individual outputs"""
# diversity in terms of cosine distances between features
feature_correlations = np.zeros(X.shape[0]-1)
for i in np.arange(1,X.shape[0]-1):
feature_corr... |
returns an roc auc score depending on the underlying estimator.
def roc_auc_cv(self,features,labels):
"""returns an roc auc score depending on the underlying estimator."""
if callable(getattr(self.ml, "decision_function", None)):
return np.mean([self.scoring_function(labels[test],
... |
safe division
def divs(x,y):
"""safe division"""
tmp = np.ones(x.shape)
nonzero_y = y != 0
tmp[nonzero_y] = x[nonzero_y]/y[nonzero_y]
return tmp |
safe log
def logs(x):
"""safe log"""
tmp = np.ones(x.shape)
nonzero_x = x != 0
tmp[nonzero_x] = np.log(np.abs(x[nonzero_x]))
return tmp |
returns non-aggregate version of r2 score.
based on r2_score() function from sklearn (http://sklearn.org)
def r2_score_vec(y_true,y_pred):
""" returns non-aggregate version of r2 score.
based on r2_score() function from sklearn (http://sklearn.org)
"""
numerator = (y_true - y_pred) ** 2
deno... |
return the within-class squared distance from the centroid
def inertia(X,y,samples=False):
""" return the within-class squared distance from the centroid"""
# pdb.set_trace()
if samples:
# return within-class distance for each sample
inertia = np.zeros(y.shape)
for label in np.uniqu... |
return the sum of the between-class squared distance
def separation(X,y,samples=False):
""" return the sum of the between-class squared distance"""
# pdb.set_trace()
num_classes = len(np.unique(y))
total_dist = (X.max()-X.min())**2
if samples:
# return intra-class distance for each sample
... |
Fisher criterion
def fisher(yhat,y,samples=False):
"""Fisher criterion"""
classes = np.unique(y)
mu = np.zeros(len(classes))
v = np.zeros(len(classes))
# pdb.set_trace()
for c in classes.astype(int):
mu[c] = np.mean(yhat[y==c])
v[c] = np.var(yhat[y==c])
if not samples:
... |
cleans fitness vector
def proper(self,x):
"""cleans fitness vector"""
x[x < 0] = self.max_fit
x[np.isnan(x)] = self.max_fit
x[np.isinf(x)] = self.max_fit
return x |
removes nans and infs from outputs.
def safe(self,x):
"""removes nans and infs from outputs."""
x[np.isinf(x)] = 1
x[np.isnan(x)] = 1
return x |
evaluate node in program
def evaluate(self,n, features, stack_float, stack_bool,labels=None):
"""evaluate node in program"""
np.seterr(all='ignore')
if len(stack_float) >= n.arity['f'] and len(stack_bool) >= n.arity['b']:
if n.out_type == 'f':
stack_float.append(
... |
returns true if X is finite, false, otherwise
def all_finite(self,X):
"""returns true if X is finite, false, otherwise"""
# Adapted from sklearn utils: _assert_all_finite(X)
# First try an O(n) time, O(1) space solution for the common case that
# everything is finite; fall back to O(n) ... |
computes the output for individual I
def out(self,I,features,labels=None,otype='f'):
"""computes the output for individual I"""
stack_float = []
stack_bool = []
# print("stack:",I.stack)
# evaulate stack over rows of features,labels
# pdb.set_trace()
for n in I.s... |
computes fitness of individual output yhat.
yhat: output of a program.
labels: correct outputs
fit_choice: choice of fitness function
def calc_fitness(self,X,labels,fit_choice,sel):
"""computes fitness of individual output yhat.
yhat: output of a program.
labels: correct... |
Converts the ImageData dictionary, imdict, to an nd image.
def imagedatadict_to_ndarray(imdict):
"""
Converts the ImageData dictionary, imdict, to an nd image.
"""
arr = imdict['Data']
im = None
if isinstance(arr, parse_dm3.array.array):
im = numpy.asarray(arr, dtype=arr.typecode)
e... |
Convert the numpy array nparr into a suitable ImageList entry dictionary.
Returns a dictionary with the appropriate Data, DataType, PixelDepth
to be inserted into a dm3 tag dictionary and written to a file.
def ndarray_to_imagedatadict(nparr):
"""
Convert the numpy array nparr into a suitable ImageList... |
Loads the image from the file-like object or string file.
If file is a string, the file is opened and then read.
Returns a numpy ndarray of our best guess for the most important image
in the file.
def load_image(file) -> DataAndMetadata.DataAndMetadata:
"""
Loads the image from the file-like object... |
Saves the nparray data to the file-like object (or string) file.
def save_image(xdata: DataAndMetadata.DataAndMetadata, file):
"""
Saves the nparray data to the file-like object (or string) file.
"""
# we need to create a basic DM tree suitable for an image
# we'll try the minimum: just an data lis... |
This is the start of the DM file. We check for some
magic values and then treat the next entry as a tag_root
If outdata is supplied, we write instead of read using the dictionary outdata as a source
Hopefully parse_dm_header(newf, outdata=parse_dm_header(f)) copies f to newf
def parse_dm_header(f, outdata... |
Return structchar, dmtype for the python (or numpy)
type or object typeorobj.
For more complex types we only return the dm type
def get_structdmtypes_for_python_typeorobject(typeorobj):
"""
Return structchar, dmtype for the python (or numpy)
type or object typeorobj.
For more complex types we o... |
datatype_num is the number of the data type, see dm_simple_names
above. desc is a (nicename, struct_char) tuple. We return a function
that parses the data for us.
def standard_dm_read(datatype_num, desc):
"""
datatype_num is the number of the data type, see dm_simple_names
above. desc is a (nicenam... |
Return image data from TIFF file(s) as numpy array.
Refer to the TiffFile and TiffSequence classes and their asarray
functions for documentation.
Parameters
----------
files : str, binary stream, or sequence
File name, seekable binary stream, glob pattern, or sequence of
file name... |
Write numpy array to TIFF file.
Refer to the TiffWriter class and its asarray function for documentation.
A BigTIFF file is created if the data size in bytes is larger than 4 GB
minus 32 MB (for metadata), and 'bigtiff' is not specified, and 'imagej'
or 'truncate' are not enabled.
Parameters
... |
Return memory-mapped numpy array stored in TIFF file.
Memory-mapping requires data stored in native byte order, without tiling,
compression, predictors, etc.
If 'shape' and 'dtype' are provided, existing files will be overwritten or
appended to depending on the 'append' parameter.
Otherwise the ima... |
Read tags from chain of IFDs and return as list of dicts.
The file handle position must be at a valid IFD header.
def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None,
maxifds=None):
"""Read tags from chain of IFDs and return as list of dicts.
The file handle position must be ... |
Read EXIF tags from file and return as dict.
def read_exif_ifd(fh, byteorder, dtype, count, offsetsize):
"""Read EXIF tags from file and return as dict."""
exif = read_tags(fh, byteorder, offsetsize, TIFF.EXIF_TAGS, maxifds=1)
for name in ('ExifVersion', 'FlashpixVersion'):
try:
exif[na... |
Read GPS tags from file and return as dict.
def read_gps_ifd(fh, byteorder, dtype, count, offsetsize):
"""Read GPS tags from file and return as dict."""
return read_tags(fh, byteorder, offsetsize, TIFF.GPS_TAGS, maxifds=1) |
Read Interoperability tags from file and return as dict.
def read_interoperability_ifd(fh, byteorder, dtype, count, offsetsize):
"""Read Interoperability tags from file and return as dict."""
tag_names = {1: 'InteroperabilityIndex'}
return read_tags(fh, byteorder, offsetsize, tag_names, maxifds=1) |
Read tag data from file and return as byte string.
def read_bytes(fh, byteorder, dtype, count, offsetsize):
"""Read tag data from file and return as byte string."""
dtype = 'B' if dtype[-1] == 's' else byteorder+dtype[-1]
count *= numpy.dtype(dtype).itemsize
data = fh.read(count)
if len(data) != co... |
Read tag data from file and return as unicode string.
def read_utf8(fh, byteorder, dtype, count, offsetsize):
"""Read tag data from file and return as unicode string."""
return fh.read(count).decode('utf-8') |
Read tag data from file and return as numpy array.
def read_numpy(fh, byteorder, dtype, count, offsetsize):
"""Read tag data from file and return as numpy array."""
dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]
return fh.read_array(dtype, count) |
Read ColorMap data from file and return as numpy array.
def read_colormap(fh, byteorder, dtype, count, offsetsize):
"""Read ColorMap data from file and return as numpy array."""
cmap = fh.read_array(byteorder+dtype[-1], count)
cmap.shape = (3, -1)
return cmap |
Read JSON tag data from file and return as object.
def read_json(fh, byteorder, dtype, count, offsetsize):
"""Read JSON tag data from file and return as object."""
data = fh.read(count)
try:
return json.loads(unicode(stripnull(data), 'utf-8'))
except ValueError:
log.warning('read_json: ... |
Read FluoView mm_header tag from file and return as dict.
def read_mm_header(fh, byteorder, dtype, count, offsetsize):
"""Read FluoView mm_header tag from file and return as dict."""
mmh = fh.read_record(TIFF.MM_HEADER, byteorder=byteorder)
mmh = recarray2dict(mmh)
mmh['Dimensions'] = [
(bytes2... |
Read MetaMorph STK UIC1Tag from file and return as dict.
Return empty dictionary if planecount is unknown.
def read_uic1tag(fh, byteorder, dtype, count, offsetsize, planecount=None):
"""Read MetaMorph STK UIC1Tag from file and return as dict.
Return empty dictionary if planecount is unknown.
"""
... |
Read MetaMorph STK UIC2Tag from file and return as dict.
def read_uic2tag(fh, byteorder, dtype, planecount, offsetsize):
"""Read MetaMorph STK UIC2Tag from file and return as dict."""
assert dtype == '2I' and byteorder == '<'
values = fh.read_array('<u4', 6*planecount).reshape(planecount, 6)
return {
... |
Read MetaMorph STK UIC4Tag from file and return as dict.
def read_uic4tag(fh, byteorder, dtype, planecount, offsetsize):
"""Read MetaMorph STK UIC4Tag from file and return as dict."""
assert dtype == '1I' and byteorder == '<'
result = {}
while True:
tagid = struct.unpack('<H', fh.read(2))[0]
... |
Read a single UIC tag value from file and return tag name and value.
UIC1Tags use an offset.
def read_uic_tag(fh, tagid, planecount, offset):
"""Read a single UIC tag value from file and return tag name and value.
UIC1Tags use an offset.
"""
def read_int(count=1):
value = struct.unpack('... |
Read UIC ImagePropertyEx tag from file and return as dict.
def read_uic_image_property(fh):
"""Read UIC ImagePropertyEx tag from file and return as dict."""
# TODO: test this
size = struct.unpack('B', fh.read(1))[0]
name = struct.unpack('%is' % size, fh.read(size))[0][:-1]
flags, prop = struct.unpa... |
Read CZ_LSMINFO tag from file and return as dict.
def read_cz_lsminfo(fh, byteorder, dtype, count, offsetsize):
"""Read CZ_LSMINFO tag from file and return as dict."""
assert byteorder == '<'
magic_number, structure_size = struct.unpack('<II', fh.read(8))
if magic_number not in (50350412, 67127628):
... |
Read LSM sequence of float pairs from file and return as list.
def read_lsm_floatpairs(fh):
"""Read LSM sequence of float pairs from file and return as list."""
size = struct.unpack('<i', fh.read(4))[0]
return fh.read_array('<2f8', count=size) |
Read LSM positions from file and return as list.
def read_lsm_positions(fh):
"""Read LSM positions from file and return as list."""
size = struct.unpack('<I', fh.read(4))[0]
return fh.read_array('<2f8', count=size) |
Read LSM time stamps from file and return as list.
def read_lsm_timestamps(fh):
"""Read LSM time stamps from file and return as list."""
size, count = struct.unpack('<ii', fh.read(8))
if size != (8 + 8 * count):
log.warning('read_lsm_timestamps: invalid LSM TimeStamps block')
return []
... |
Read LSM events from file and return as list of (time, type, text).
def read_lsm_eventlist(fh):
"""Read LSM events from file and return as list of (time, type, text)."""
count = struct.unpack('<II', fh.read(8))[1]
events = []
while count > 0:
esize, etime, etype = struct.unpack('<IdI', fh.read(... |
Read LSM ChannelColors structure from file and return as dict.
def read_lsm_channelcolors(fh):
"""Read LSM ChannelColors structure from file and return as dict."""
result = {'Mono': False, 'Colors': [], 'ColorNames': []}
pos = fh.tell()
(size, ncolors, nnames,
coffset, noffset, mono) = struct.unpa... |
Read LSM ScanInfo structure from file and return as dict.
def read_lsm_scaninfo(fh):
"""Read LSM ScanInfo structure from file and return as dict."""
block = {}
blocks = [block]
unpack = struct.unpack
if struct.unpack('<I', fh.read(4))[0] != 0x10000000:
# not a Recording sub block
lo... |
Read OlympusSIS structure and return as dict.
No specification is avaliable. Only few fields are known.
def read_sis(fh, byteorder, dtype, count, offsetsize):
"""Read OlympusSIS structure and return as dict.
No specification is avaliable. Only few fields are known.
"""
result = {}
(magic, _... |
Read OlympusSIS INI string and return as dict.
def read_sis_ini(fh, byteorder, dtype, count, offsetsize):
"""Read OlympusSIS INI string and return as dict."""
inistr = fh.read(count)
inistr = bytes2str(stripnull(inistr))
try:
return olympusini_metadata(inistr)
except Exception as exc:
... |
Read TVIPS EM-MENU headers and return as dict.
def read_tvips_header(fh, byteorder, dtype, count, offsetsize):
"""Read TVIPS EM-MENU headers and return as dict."""
result = {}
header = fh.read_record(TIFF.TVIPS_HEADER_V1, byteorder=byteorder)
for name, typestr in TIFF.TVIPS_HEADER_V1:
result[na... |
Read FEI SFEG/HELIOS headers and return as dict.
def read_fei_metadata(fh, byteorder, dtype, count, offsetsize):
"""Read FEI SFEG/HELIOS headers and return as dict."""
result = {}
section = {}
data = bytes2str(stripnull(fh.read(count)))
for line in data.splitlines():
line = line.strip()
... |
Read Zeiss SEM tag and return as dict.
See https://sourceforge.net/p/gwyddion/mailman/message/29275000/ for
unnamed values.
def read_cz_sem(fh, byteorder, dtype, count, offsetsize):
"""Read Zeiss SEM tag and return as dict.
See https://sourceforge.net/p/gwyddion/mailman/message/29275000/ for
unna... |
Read NIH_IMAGE_HEADER tag from file and return as dict.
def read_nih_image_header(fh, byteorder, dtype, count, offsetsize):
"""Read NIH_IMAGE_HEADER tag from file and return as dict."""
a = fh.read_record(TIFF.NIH_IMAGE_HEADER, byteorder=byteorder)
a = a.newbyteorder(byteorder)
a = recarray2dict(a)
... |
Read ScanImage BigTIFF v3 static and ROI metadata from open file.
Return non-varying frame data as dict and ROI group data as JSON.
The settings can be used to read image data and metadata without parsing
the TIFF file.
Raise ValueError if file does not contain valid ScanImage v3 metadata.
def read_... |
Read MicroManager non-TIFF settings from open file and return as dict.
The settings can be used to read image data without parsing the TIFF file.
Raise ValueError if the file does not contain valid MicroManager metadata.
def read_micromanager_metadata(fh):
"""Read MicroManager non-TIFF settings from open... |
Return IJMetadata and IJMetadataByteCounts tags from metadata dict.
The tags can be passed to the TiffWriter.save function as extratags.
The metadata dict may contain the following keys and values:
Info : str
Human-readable information as string.
Labels : sequence of str
... |
Return IJMetadata tag value as dict.
The 'Info' string can have multiple formats, e.g. OIF or ScanImage,
that might be parsed into dicts using the matlabstr2py or
oiffile.SettingsFile functions.
def imagej_metadata(data, bytecounts, byteorder):
"""Return IJMetadata tag value as dict.
The 'Info' s... |
Return metatata from ImageJ image description as dict.
Raise ValueError if not a valid ImageJ description.
>>> description = 'ImageJ=1.11a\\nimages=510\\nhyperstack=true\\n'
>>> imagej_description_metadata(description) # doctest: +SKIP
{'ImageJ': '1.11a', 'images': 510, 'hyperstack': True}
def image... |
Return ImageJ image description from data shape.
ImageJ can handle up to 6 dimensions in order TZCYXS.
>>> imagej_description((51, 5, 2, 196, 171)) # doctest: +SKIP
ImageJ=1.11a
images=510
channels=2
slices=5
frames=51
hyperstack=true
mode=grayscale
loop=false
def imagej_desc... |
Return shape normalized to 6D ImageJ hyperstack TZCYXS.
Raise ValueError if not a valid ImageJ hyperstack shape.
>>> imagej_shape((2, 3, 4, 5, 3), False)
(2, 3, 4, 5, 3, 1)
def imagej_shape(shape, rgb=None):
"""Return shape normalized to 6D ImageJ hyperstack TZCYXS.
Raise ValueError if not a val... |
Return JSON image description from data shape and other metadata.
Return UTF-8 encoded JSON.
>>> json_description((256, 256, 3), axes='YXS') # doctest: +SKIP
b'{"shape": [256, 256, 3], "axes": "YXS"}'
def json_description(shape, **metadata):
"""Return JSON image description from data shape and other... |
Return metatata from JSON formated image description as dict.
Raise ValuError if description is of unknown format.
>>> description = '{"shape": [256, 256, 3], "axes": "YXS"}'
>>> json_description_metadata(description) # doctest: +SKIP
{'shape': [256, 256, 3], 'axes': 'YXS'}
>>> json_description_m... |
Return metatata from FluoView image description as dict.
The FluoView image description format is unspecified. Expect failures.
>>> descr = ('[Intensity Mapping]\\nMap Ch0: Range=00000 to 02047\\n'
... '[Intensity Mapping End]')
>>> fluoview_description_metadata(descr)
{'Intensity Mapping... |
Return metatata from Pilatus image description as dict.
Return metadata from Pilatus pixel array detectors by Dectris, created
by camserver or TVX software.
>>> pilatus_description_metadata('# Pixel_size 172e-6 m x 172e-6 m')
{'Pixel_size': (0.000172, 0.000172)}
def pilatus_description_metadata(descr... |
Return metatata from Aperio image description as dict.
The Aperio image description format is unspecified. Expect failures.
>>> svs_description_metadata('Aperio Image Library v1.0')
{'Aperio Image Library': 'v1.0'}
def svs_description_metadata(description):
"""Return metatata from Aperio image descri... |
Return metadata from MetaMorph image description as list of dict.
The MetaMorph image description format is unspecified. Expect failures.
def stk_description_metadata(description):
"""Return metadata from MetaMorph image description as list of dict.
The MetaMorph image description format is unspecified. ... |
Return metatata from MetaSeries image description as dict.
def metaseries_description_metadata(description):
"""Return metatata from MetaSeries image description as dict."""
if not description.startswith('<MetaData>'):
raise ValueError('invalid MetaSeries image description')
from xml.etree import ... |
Return metatata from ScanImage artist tag as dict.
def scanimage_artist_metadata(artist):
"""Return metatata from ScanImage artist tag as dict."""
try:
return json.loads(artist)
except ValueError as exc:
log.warning('scanimage_artist_metadata: %s: %s',
exc.__class__.__na... |
Return OlympusSIS metadata from INI string.
No documentation is available.
def olympusini_metadata(inistr):
"""Return OlympusSIS metadata from INI string.
No documentation is available.
"""
def keyindex(key):
# split key into name and index
index = 0
i = len(key.rstrip('0... |
Decode tile segment bytes into 5D output array.
def tile_decode(tile, tileindex, tileshape, tiledshape,
lsb2msb, decompress, unpack, unpredict, out):
"""Decode tile segment bytes into 5D output array."""
_, imagedepth, imagelength, imagewidth, _ = out.shape
tileddepth, tiledlength, tiledwid... |
Return array from byte string containing packed samples.
Use to unpack RGB565 or RGB555 to RGB888 format.
Parameters
----------
data : byte str
The data to be decoded. Samples in each pixel are stored consecutively.
Pixels are aligned to 8, 16, or 32 bit boundaries.
dtype : numpy.d... |
Encode Delta.
def delta_encode(data, axis=-1, out=None):
"""Encode Delta."""
if isinstance(data, (bytes, bytearray)):
data = numpy.frombuffer(data, dtype='u1')
diff = numpy.diff(data, axis=0)
return numpy.insert(diff, 0, data[0]).tobytes()
dtype = data.dtype
if dtype.kind == 'f... |
Decode Delta.
def delta_decode(data, axis=-1, out=None):
"""Decode Delta."""
if out is not None and not out.flags.writeable:
out = None
if isinstance(data, (bytes, bytearray)):
data = numpy.frombuffer(data, dtype='u1')
return numpy.cumsum(data, axis=0, dtype='u1', out=out).tobytes()... |
Reverse bits in each byte of byte string or numpy array.
Decode data where pixels with lower column values are stored in the
lower-order bits of the bytes (TIFF FillOrder is LSB2MSB).
Parameters
----------
data : byte string or ndarray
The data to be bit reversed. If byte string, a new bit... |
Decompress byte string to array of integers.
This implementation only handles itemsizes 1, 8, 16, 32, and 64 bits.
Install the imagecodecs package for decoding other integer sizes.
Parameters
----------
data : byte str
Data to decompress.
dtype : numpy.dtype or str
A numpy bool... |
Return palette-colored image.
The image values are used to index the colormap on axis 1. The returned
image is of shape image.shape+colormap.shape[0] and dtype colormap.dtype.
Parameters
----------
image : numpy.ndarray
Indexes into the colormap.
colormap : numpy.ndarray
RGB lo... |
Return reoriented view of image array.
Parameters
----------
image : numpy.ndarray
Non-squeezed output of asarray() functions.
Axes -3 and -2 must be image length and width respectively.
orientation : int or str
One of TIFF.ORIENTATION names or values.
def reorient(image, orien... |
Return read-only view into input array with elements repeated.
Zoom nD image by integer factors using nearest neighbor interpolation
(box filter).
Parameters
----------
a : array_like
Input array.
repeats : sequence of int
The number of repetitions to apply along each dimension... |
Return image array or shape with at least ndim dimensions.
Prepend 1s to image shape as necessary.
>>> reshape_nd(numpy.empty(0), 1).shape
(0,)
>>> reshape_nd(numpy.empty(1), 2).shape
(1, 1)
>>> reshape_nd(numpy.empty((2, 3)), 3).shape
(1, 2, 3)
>>> reshape_nd(numpy.empty((3, 4, 5)), 3... |
Return shape and axes with single-dimensional entries removed.
Remove unused dimensions unless their axes are listed in 'skip'.
>>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
((5, 2, 1), 'TYX')
def squeeze_axes(shape, axes, skip=None):
"""Return shape and axes with single-dimensional entries removed.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.