How to use force_copy method in autotest

Best Python code snippet using autotest_python

dtype.py

Source:dtype.py Github

copy

Full Screen

1'''2Contains code from scikit-image v0.18.33'''4import numpy as np5from warnings import warn6# For integers Numpy uses `_integer_types` basis internally, and builds a leaky7# `np.XintYY` abstraction on top of it. This leads to situations when, for8# example, there are two np.Xint64 dtypes with the same attributes but9# different object references. In order to avoid any potential issues,10# we use the basis dtypes here. For more information, see:11# - https://github.com/scikit-image/scikit-image/issues/304312# For convenience, for these dtypes we indicate also the possible bit depths13# (some of them are platform specific). For the details, see:14# http://www.unix.org/whitepapers/64bit.html15_integer_types = (np.byte, np.ubyte, # 8 bits16 np.short, np.ushort, # 16 bits17 np.intc, np.uintc, # 16 or 32 or 64 bits18 int, np.int_, np.uint, # 32 or 64 bits19 np.longlong, np.ulonglong) # 64 bits20_integer_ranges = {t: (np.iinfo(t).min, np.iinfo(t).max)21 for t in _integer_types}22dtype_range = {bool: (False, True),23 np.bool_: (False, True),24 np.bool8: (False, True),25 float: (-1, 1),26 np.float_: (-1, 1),27 np.float16: (-1, 1),28 np.float32: (-1, 1),29 np.float64: (-1, 1)}30dtype_range.update(_integer_ranges)31_supported_types = list(dtype_range.keys())32def dtype_limits(image, clip_negative=False):33 """Return intensity limits, i.e. (min, max) tuple, of the image's dtype.34 Parameters35 ----------36 image : ndarray37 Input image.38 clip_negative : bool, optional39 If True, clip the negative range (i.e. return 0 for min intensity)40 even if the image dtype allows negative values.41 Returns42 -------43 imin, imax : tuple44 Lower and upper intensity limits.45 """46 imin, imax = dtype_range[image.dtype.type]47 if clip_negative:48 imin = 049 return imin, imax50def _dtype_itemsize(itemsize, *dtypes):51 """Return first of `dtypes` with itemsize greater than `itemsize`52 Parameters53 ----------54 itemsize: int55 The data type object element size.56 Other Parameters57 ----------------58 *dtypes:59 Any Object accepted by `np.dtype` to be converted to a data60 type object61 Returns62 -------63 dtype: data type object64 First of `dtypes` with itemsize greater than `itemsize`.65 """66 return next(dt for dt in dtypes if np.dtype(dt).itemsize >= itemsize)67def _dtype_bits(kind, bits, itemsize=1):68 """Return dtype of `kind` that can store a `bits` wide unsigned int69 Parameters:70 kind: str71 Data type kind.72 bits: int73 Desired number of bits.74 itemsize: int75 The data type object element size.76 Returns77 -------78 dtype: data type object79 Data type of `kind` that can store a `bits` wide unsigned int80 """81 s = next(i for i in (itemsize, ) + (2, 4, 8) if82 bits < (i * 8) or (bits == (i * 8) and kind == 'u'))83 return np.dtype(kind + str(s))84def _scale(a, n, m, copy=True):85 """Scale an array of unsigned/positive integers from `n` to `m` bits.86 Numbers can be represented exactly only if `m` is a multiple of `n`.87 Parameters88 ----------89 a : ndarray90 Input image array.91 n : int92 Number of bits currently used to encode the values in `a`.93 m : int94 Desired number of bits to encode the values in `out`.95 copy : bool, optional96 If True, allocates and returns new array. Otherwise, modifies97 `a` in place.98 Returns99 -------100 out : array101 Output image array. Has the same kind as `a`.102 """103 kind = a.dtype.kind104 if n > m and a.max() < 2 ** m:105 mnew = int(np.ceil(m / 2) * 2)106 if mnew > m:107 dtype = "int{}".format(mnew)108 else:109 dtype = "uint{}".format(mnew)110 n = int(np.ceil(n / 2) * 2)111 warn("Downcasting {} to {} without scaling because max "112 "value {} fits in {}".format(a.dtype, dtype, a.max(), dtype),113 stacklevel=3)114 return a.astype(_dtype_bits(kind, m))115 elif n == m:116 return a.copy() if copy else a117 elif n > m:118 # downscale with precision loss119 if copy:120 b = np.empty(a.shape, _dtype_bits(kind, m))121 np.floor_divide(a, 2**(n - m), out=b, dtype=a.dtype,122 casting='unsafe')123 return b124 else:125 a //= 2**(n - m)126 return a127 elif m % n == 0:128 # exact upscale to a multiple of `n` bits129 if copy:130 b = np.empty(a.shape, _dtype_bits(kind, m))131 np.multiply(a, (2**m - 1) // (2**n - 1), out=b, dtype=b.dtype)132 return b133 else:134 a = a.astype(_dtype_bits(kind, m, a.dtype.itemsize), copy=False)135 a *= (2**m - 1) // (2**n - 1)136 return a137 else:138 # upscale to a multiple of `n` bits,139 # then downscale with precision loss140 o = (m // n + 1) * n141 if copy:142 b = np.empty(a.shape, _dtype_bits(kind, o))143 np.multiply(a, (2**o - 1) // (2**n - 1), out=b, dtype=b.dtype)144 b //= 2**(o - m)145 return b146 else:147 a = a.astype(_dtype_bits(kind, o, a.dtype.itemsize), copy=False)148 a *= (2**o - 1) // (2**n - 1)149 a //= 2**(o - m)150 return a151def _convert(image, dtype, force_copy=False, uniform=False):152 """153 Convert an image to the requested data-type.154 Warnings are issued in case of precision loss, or when negative values155 are clipped during conversion to unsigned integer types (sign loss).156 Floating point values are expected to be normalized and will be clipped157 to the range [0.0, 1.0] or [-1.0, 1.0] when converting to unsigned or158 signed integers respectively.159 Numbers are not shifted to the negative side when converting from160 unsigned to signed integer types. Negative values will be clipped when161 converting to unsigned integers.162 Parameters163 ----------164 image : ndarray165 Input image.166 dtype : dtype167 Target data-type.168 force_copy : bool, optional169 Force a copy of the data, irrespective of its current dtype.170 uniform : bool, optional171 Uniformly quantize the floating point range to the integer range.172 By default (uniform=False) floating point values are scaled and173 rounded to the nearest integers, which minimizes back and forth174 conversion errors.175 .. versionchanged :: 0.15176 ``_convert`` no longer warns about possible precision or sign177 information loss. See discussions on these warnings at:178 https://github.com/scikit-image/scikit-image/issues/2602179 https://github.com/scikit-image/scikit-image/issues/543#issuecomment-208202228180 https://github.com/scikit-image/scikit-image/pull/3575181 References182 ----------183 .. [1] DirectX data conversion rules.184 https://msdn.microsoft.com/en-us/library/windows/desktop/dd607323%28v=vs.85%29.aspx185 .. [2] Data Conversions. In "OpenGL ES 2.0 Specification v2.0.25",186 pp 7-8. Khronos Group, 2010.187 .. [3] Proper treatment of pixels as integers. A.W. Paeth.188 In "Graphics Gems I", pp 249-256. Morgan Kaufmann, 1990.189 .. [4] Dirty Pixels. J. Blinn. In "Jim Blinn's corner: Dirty Pixels",190 pp 47-57. Morgan Kaufmann, 1998.191 """192 image = np.asarray(image)193 dtypeobj_in = image.dtype194 if dtype is np.floating:195 dtypeobj_out = np.dtype('float64')196 else:197 dtypeobj_out = np.dtype(dtype)198 dtype_in = dtypeobj_in.type199 dtype_out = dtypeobj_out.type200 kind_in = dtypeobj_in.kind201 kind_out = dtypeobj_out.kind202 itemsize_in = dtypeobj_in.itemsize203 itemsize_out = dtypeobj_out.itemsize204 # Below, we do an `issubdtype` check. Its purpose is to find out205 # whether we can get away without doing any image conversion. This happens206 # when:207 #208 # - the output and input dtypes are the same or209 # - when the output is specified as a type, and the input dtype210 # is a subclass of that type (e.g. `np.floating` will allow211 # `float32` and `float64` arrays through)212 if np.issubdtype(dtype_in, np.obj2sctype(dtype)):213 if force_copy:214 image = image.copy()215 return image216 if not (dtype_in in _supported_types and dtype_out in _supported_types):217 raise ValueError("Can not convert from {} to {}."218 .format(dtypeobj_in, dtypeobj_out))219 if kind_in in 'ui':220 imin_in = np.iinfo(dtype_in).min221 imax_in = np.iinfo(dtype_in).max222 if kind_out in 'ui':223 imin_out = np.iinfo(dtype_out).min224 imax_out = np.iinfo(dtype_out).max225 # any -> binary226 if kind_out == 'b':227 return image > dtype_in(dtype_range[dtype_in][1] / 2)228 # binary -> any229 if kind_in == 'b':230 result = image.astype(dtype_out)231 if kind_out != 'f':232 result *= dtype_out(dtype_range[dtype_out][1])233 return result234 # float -> any235 if kind_in == 'f':236 if kind_out == 'f':237 # float -> float238 return image.astype(dtype_out)239 if np.min(image) < -1.0 or np.max(image) > 1.0:240 raise ValueError("Images of type float must be between -1 and 1.")241 # floating point -> integer242 # use float type that can represent output integer type243 computation_type = _dtype_itemsize(itemsize_out, dtype_in,244 np.float32, np.float64)245 if not uniform:246 if kind_out == 'u':247 image_out = np.multiply(image, imax_out,248 dtype=computation_type)249 else:250 image_out = np.multiply(image, (imax_out - imin_out) / 2,251 dtype=computation_type)252 image_out -= 1.0 / 2.253 np.rint(image_out, out=image_out)254 np.clip(image_out, imin_out, imax_out, out=image_out)255 elif kind_out == 'u':256 image_out = np.multiply(image, imax_out + 1,257 dtype=computation_type)258 np.clip(image_out, 0, imax_out, out=image_out)259 else:260 image_out = np.multiply(image, (imax_out - imin_out + 1.0) / 2.0,261 dtype=computation_type)262 np.floor(image_out, out=image_out)263 np.clip(image_out, imin_out, imax_out, out=image_out)264 return image_out.astype(dtype_out)265 # signed/unsigned int -> float266 if kind_out == 'f':267 # use float type that can exactly represent input integers268 computation_type = _dtype_itemsize(itemsize_in, dtype_out,269 np.float32, np.float64)270 if kind_in == 'u':271 # using np.divide or np.multiply doesn't copy the data272 # until the computation time273 image = np.multiply(image, 1. / imax_in,274 dtype=computation_type)275 # DirectX uses this conversion also for signed ints276 # if imin_in:277 # np.maximum(image, -1.0, out=image)278 else:279 image = np.add(image, 0.5, dtype=computation_type)280 image *= 2 / (imax_in - imin_in)281 return np.asarray(image, dtype_out)282 # unsigned int -> signed/unsigned int283 if kind_in == 'u':284 if kind_out == 'i':285 # unsigned int -> signed int286 image = _scale(image, 8 * itemsize_in, 8 * itemsize_out - 1)287 return image.view(dtype_out)288 else:289 # unsigned int -> unsigned int290 return _scale(image, 8 * itemsize_in, 8 * itemsize_out)291 # signed int -> unsigned int292 if kind_out == 'u':293 image = _scale(image, 8 * itemsize_in - 1, 8 * itemsize_out)294 result = np.empty(image.shape, dtype_out)295 np.maximum(image, 0, out=result, dtype=image.dtype, casting='unsafe')296 return result297 # signed int -> signed int298 if itemsize_in > itemsize_out:299 return _scale(image, 8 * itemsize_in - 1, 8 * itemsize_out - 1)300 image = image.astype(_dtype_bits('i', itemsize_out * 8))301 image -= imin_in302 image = _scale(image, 8 * itemsize_in, 8 * itemsize_out, copy=False)303 image += imin_out304 return image.astype(dtype_out)305def convert(image, dtype, force_copy=False, uniform=False):306 warn("The use of this function is discouraged as its behavior may change "307 "dramatically in scikit-image 1.0. This function will be removed"308 "in scikit-image 1.0.", FutureWarning, stacklevel=2)309 return _convert(image=image, dtype=dtype,310 force_copy=force_copy, uniform=uniform)311if _convert.__doc__ is not None:312 convert.__doc__ = _convert.__doc__ + """313 Warns314 -----315 FutureWarning:316 .. versionadded:: 0.17317 The use of this function is discouraged as its behavior may change318 dramatically in scikit-image 1.0. This function will be removed319 in scikit-image 1.0.320 """321def img_as_float32(image, force_copy=False):322 """Convert an image to single-precision (32-bit) floating point format.323 Parameters324 ----------325 image : ndarray326 Input image.327 force_copy : bool, optional328 Force a copy of the data, irrespective of its current dtype.329 Returns330 -------331 out : ndarray of float32332 Output image.333 Notes334 -----335 The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when336 converting from unsigned or signed datatypes, respectively.337 If the input image has a float type, intensity values are not modified338 and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].339 """340 return _convert(image, np.float32, force_copy)341def img_as_float64(image, force_copy=False):342 """Convert an image to double-precision (64-bit) floating point format.343 Parameters344 ----------345 image : ndarray346 Input image.347 force_copy : bool, optional348 Force a copy of the data, irrespective of its current dtype.349 Returns350 -------351 out : ndarray of float64352 Output image.353 Notes354 -----355 The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when356 converting from unsigned or signed datatypes, respectively.357 If the input image has a float type, intensity values are not modified358 and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].359 """360 return _convert(image, np.float64, force_copy)361def img_as_float(image, force_copy=False):362 """Convert an image to floating point format.363 This function is similar to `img_as_float64`, but will not convert364 lower-precision floating point arrays to `float64`.365 Parameters366 ----------367 image : ndarray368 Input image.369 force_copy : bool, optional370 Force a copy of the data, irrespective of its current dtype.371 Returns372 -------373 out : ndarray of float374 Output image.375 Notes376 -----377 The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when378 converting from unsigned or signed datatypes, respectively.379 If the input image has a float type, intensity values are not modified380 and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].381 """382 return _convert(image, np.floating, force_copy)383def img_as_uint(image, force_copy=False):384 """Convert an image to 16-bit unsigned integer format.385 Parameters386 ----------387 image : ndarray388 Input image.389 force_copy : bool, optional390 Force a copy of the data, irrespective of its current dtype.391 Returns392 -------393 out : ndarray of uint16394 Output image.395 Notes396 -----397 Negative input values will be clipped.398 Positive values are scaled between 0 and 65535.399 """400 return _convert(image, np.uint16, force_copy)401def img_as_int(image, force_copy=False):402 """Convert an image to 16-bit signed integer format.403 Parameters404 ----------405 image : ndarray406 Input image.407 force_copy : bool, optional408 Force a copy of the data, irrespective of its current dtype.409 Returns410 -------411 out : ndarray of int16412 Output image.413 Notes414 -----415 The values are scaled between -32768 and 32767.416 If the input data-type is positive-only (e.g., uint8), then417 the output image will still only have positive values.418 """419 return _convert(image, np.int16, force_copy)420def img_as_ubyte(image, force_copy=False):421 """Convert an image to 8-bit unsigned integer format.422 Parameters423 ----------424 image : ndarray425 Input image.426 force_copy : bool, optional427 Force a copy of the data, irrespective of its current dtype.428 Returns429 -------430 out : ndarray of ubyte (uint8)431 Output image.432 Notes433 -----434 Negative input values will be clipped.435 Positive values are scaled between 0 and 255.436 """437 return _convert(image, np.uint8, force_copy)438def img_as_bool(image, force_copy=False):439 """Convert an image to boolean format.440 Parameters441 ----------442 image : ndarray443 Input image.444 force_copy : bool, optional445 Force a copy of the data, irrespective of its current dtype.446 Returns447 -------448 out : ndarray of bool (`bool_`)449 Output image.450 Notes451 -----452 The upper half of the input dtype's positive range is True, and the lower453 half is False. All negative values (if present) are False.454 """...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful