def toccd(a, newshape, set_total=None): ''' Clone of oaalib's toccd() function, using least common multiple to rebin an array similar to opencv's INTER_AREA interpolation. ''' if a.shape == newshape: return a if len(a.shape) != 2: raise ValueError( 'Input array shape is %s instead of 2d, cannot continue:' % str(a.shape)) if len(newshape) != 2: raise ValueError('Output shape is %s instead of 2d, cannot continue' % str(newshape)) if set_total is None: set_total = a.sum() mcmx = lcm(a.shape[0], newshape[0]) mcmy = lcm(a.shape[1], newshape[1]) temp = rebin(a, (mcmx, a.shape[1]), sample=True) temp = rebin(temp, (newshape[0], a.shape[1])) temp = rebin(temp, (newshape[0], mcmy), sample=True) rebinned = rebin(temp, newshape) return rebinned / rebinned.sum() * set_total
def test_wrong_newshape(self): a = np.arange(4).reshape((2, 2)) with self.assertRaises(ValueError): _ = rebin(a, [4, 6, 8]) with self.assertRaises(ValueError): _ = rebin(a, ['4.0', 6])
def test_newshape_types(self): a = np.arange(4).reshape((2, 2)) b = rebin(a, [4, 6]) np.testing.assert_array_equal(b, self.ref) c = rebin(a, map(int, '4 6'.split())) np.testing.assert_array_equal(c, self.ref) c = rebin(a, map(int, ['4', 6])) np.testing.assert_array_equal(c, self.ref)
def test_exceptions(self): a = np.arange(16).reshape((4, 4)) with self.assertRaises(ValueError): _ = rebin(a, (7, 7)) with self.assertRaises(ValueError): _ = rebin(a, (3, 3)) with self.assertRaises(NotImplementedError): _ = rebin(a, (3, 7))
def test_up_sample(self): a = np.arange(4).reshape((2, 2)) b = rebin(a, (4, 6), sample=True) np.testing.assert_array_equal(b, self.ref)