Posts

Showing posts with the label Numpy

Convert Np.array Of Type Float64 To Type Uint8 Scaling Values

Answer : A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2] , the code right now would scale that to have intensities of [0, 128, 255] . You want these to remain small after converting to np.uint8 . Therefore, divide every value by the largest value possible by the image type , not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type ( dtype ) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value. So with the above, do the following modifications to your code: import numpy as np import cv2 [...] info = np.iinfo(d...

Convert A Numpy.ndarray To String(or Bytes) And Convert It Back To Numpy.ndarray

Answer : You can use the fromstring() method for this: arr = np.array([1, 2, 3, 4, 5, 6]) ts = arr.tostring() print(np.fromstring(ts, dtype=int)) >>> [1 2 3 4 5 6] Sorry for the short answer, not enough points for commenting. Remember to state the data types or you'll end up in a world of pain. Note on fromstring from numpy 1.14 onwards : sep : str, optional The string separating numbers in the data; extra whitespace between elements is also ignored. Deprecated since version 1.14: Passing sep='', the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using either utf-8 (python 3) or the default encoding (python 2), neither of which produce sane results. If you use tos...

Can I Specify A Numpy Dtype When Generating Random Values?

Answer : Q: is it possible to specify a dtype for random numbers when I create them. A: No it isn't. randn accepts the shape only as randn(d0, d1, ..., dn) Simply try this: x = np.random.randn(10, 10).astype('f') Or define a new function like np.random.randn2 = lambda *args, dtype=np.float64: np.random.randn(*args).astype(dtype) x = np.random.randn2(10, 10, dtype='f') If you have to use your code on the post, try this code instead x = np.zeros((10, 10), dtype='f') x[:] = np.random.randn(*x.shape) This assigns the results of randn to the memory allocated by np.zeros Let me begin by saying that numpy now supports dtypes for random integers. This enhancement can be tracked through Issue #6790 on numpy's github. But as of today, this facility is not available for the gaussian RNG . I needed this same facility so I wrote this patch for numpy, https://gist.github.com/se4u/e44f631b249e0be03c21c6c898059176 The patch only adds support for generati...

Calculate The Cumulative Distribution Function (CDF) In Python

Image
Answer : (It is possible that my interpretation of the question is wrong. If the question is how to get from a discrete PDF into a discrete CDF, then np.cumsum divided by a suitable constant will do if the samples are equispaced. If the array is not equispaced, then np.cumsum of the array multiplied by the distances between the points will do.) If you have a discrete array of samples, and you would like to know the CDF of the sample, then you can just sort the array. If you look at the sorted result, you'll realize that the smallest value represents 0% , and largest value represents 100 %. If you want to know the value at 50 % of the distribution, just look at the array element which is in the middle of the sorted array. Let us have a closer look at this with a simple example: import matplotlib.pyplot as plt import numpy as np # create some randomly ddistributed data: data = np.random.randn(10000) # sort the data: data_sorted = np.sort(data) # calculate the proportional ...

Absolute Difference Of Two NumPy Arrays

Answer : If you want the absolute element-wise difference between both matrices, you can easily subtract them with NumPy and use numpy.absolute on the resulting matrix. import numpy as np X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = np.absolute(np.array(X) - np.array(Y)) Outputs : [[7 1 2] [2 2 3] [3 3 0]] Alternatively ( although unnecessary ), if you were required to do so in native Python you could zip the dimensions together in a nested list comprehension. result = [[abs(a-b) for a, b in zip(xrow, yrow)] for xrow, yrow in zip(X,Y)] Outputs : [[7, 1, 2], [2, 2, 3], [3, 3, 0]] Doing this becomes trivial if you cast your 2D arrays to numpy arrays: import numpy as np X = [[12, 7, 3], [4, 5, 6], [7, 8, 9]] Y = [[5, 8, 1], [6, 7, 3], [4, 5, 9]] X, Y = map(np.array, (X, Y)) result = X - Y Numpy is designed to work easily and efficiently with matrices. Also, you spoke about subtracting mat...

Concatenate Several Np Arrays In Python

Answer : concatenate can accept a sequence of array-likes, such as args : In [11]: args = (x1, x2, x3) In [12]: xt = np.concatenate(args) In [13]: xt Out[13]: array([1, 0, 1, 0, 0, 1, 1, 1, 1]) By the way, although axis=1 works, the inputs are all 1-dimensional arrays (so they only have a 0-axis). So it makes more sense to use axis=0 or omit axis entirely since the default is axis=0 .