Beispiel #1
0
def normalize(v):
    v = list2nparray(v)
    _min, _max = min(v), max(v)
    v -= _min
    if sum(v) == 0:
        return np.ones(v.shape, 'float32') / np.prod(v.shape)
    return v / sum(v)
Beispiel #2
0
def ic01_to_i01c(arr, allow_2d=False):
    """change array of axis ('c', 0, 1) to (0, 1, 'c')"""
    arr = list2nparray(arr)
    if allow_2d and arr.ndim == 2:
        arr = arr.reshape((1, arr.shape[0], arr.shape[1]))
    assert arr.ndim == 3 and arr.shape[0] in (1, 3), arr.shape
    return np.swapaxes(np.rollaxis(arr, 1), 1, 2)
Beispiel #3
0
def i01c_to_ic01(arr, allow_2d=False, out_4d=False):
    """change array of axis (0, 1, 'c') to ('c', 0, 1)"""
    arr = list2nparray(arr)
    if allow_2d and arr.ndim == 2:
        arr = arr.reshape((arr.shape[0], arr.shape[1], 1))
    assert arr.ndim == 3 and arr.shape[2] in (1, 3), arr.shape
    arr = np.rollaxis(arr, 2)
    if out_4d:
        arr = arr.reshape((1, arr.shape[0], arr.shape[1], arr.shape[2]))
    return arr
Beispiel #4
0
def histogram(img, normalize=True):
    if img.ndim == 2:  # grayscale
        hist = cv2.calcHist([img], [0], None, [256], [0., 255.0])
        if normalize:
            hist = cv2.normalize(hist, hist, 0, 1, cv2.NORM_MINMAX)
        return hist
    else:
        hists = []
        for channel in xrange(img.shape[2]):
            hist = cv2.calcHist([img], [channel], None, [256], [0., 255.0])
            if normalize:
                hist = cv2.normalize(hist, hist, 0, 1, cv2.NORM_MINMAX)
            hists.append(hist)
        return list2nparray(hists)
Beispiel #5
0
def list2nparray(lst, dtype=None):
    """fast conversion from nested list to ndarray by pre-allocating space"""
    if isinstance(lst, np.ndarray):
        return lst
    assert isinstance(lst, (list, tuple)), 'bad type: {}'.format(type(lst))
    assert lst, 'attempt to convert empty list to np array'
    if isinstance(lst[0], np.ndarray):
        dim1 = lst[0].shape
        assert all(i.shape == dim1 for i in lst), [i.shape for i in lst]
        if dtype is None:
            dtype = lst[0].dtype
            assert all(i.dtype == dtype for i in lst), (dtype, [i.dtype for i in lst])
    elif isinstance(lst[0], (int, float, long, complex)):
        return list2nparray(lst, dtype=dtype)
    else:
        dim1 = list2nparray(lst[0])
        if dtype is None:
            dtype = dim1.dtype
        dim1 = dim1.shape
    shape = [len(lst)] + list(dim1)
    rst = np.zeros(shape, dtype=dtype)
    for idx, i in enumerate(lst):
        rst[idx] = i
    return rst
Beispiel #6
0
def cosine_similarity(v0, v1):
    a, b = list2nparray(v0, "float32"), list2nparray(v1, "float32")
    return np.dot(a, b) / math.sqrt(sum(a ** 2)) / math.sqrt(sum(b ** 2))