Python numpy.uint16() Examples

The following are 30 code examples for showing how to use numpy.uint16(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: openISP   Author: cruxopen   File: gac.py    License: MIT License 7 votes vote down vote up
def execute(self):
        img_h = self.img.shape[0]
        img_w = self.img.shape[1]
        img_c = self.img.shape[2]
        gc_img = np.empty((img_h, img_w, img_c), np.uint16)
        for y in range(self.img.shape[0]):
            for x in range(self.img.shape[1]):
                if self.mode == 'rgb':
                    gc_img[y, x, 0] = self.lut[self.img[y, x, 0]]
                    gc_img[y, x, 1] = self.lut[self.img[y, x, 1]]
                    gc_img[y, x, 2] = self.lut[self.img[y, x, 2]]
                    gc_img[y, x, :] = gc_img[y, x, :] / 4
                elif self.mode == 'yuv':
                    gc_img[y, x, 0] = self.lut[0][self.img[y, x, 0]]
                    gc_img[y, x, 1] = self.lut[1][self.img[y, x, 1]]
                    gc_img[y, x, 2] = self.lut[1][self.img[y, x, 2]]
        self.img = gc_img
        return self.img 
Example 2
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: kimotion.py    License: MIT License 6 votes vote down vote up
def __init__(self, server):
        super().__init__()
        self.setDaemon(True)
        self._stop = threading.Event()
        self._reading = thread_lock()
        self.dt = np.dtype(np.uint16)
        self.dt = self.dt.newbyteorder('<')
        self._data = [np.zeros(WS_FRAME_SIZE, self.dt),
                      np.zeros(WS_FRAME_SIZE, self.dt)]
        self._buf = False
        self.ws = create_connection("ws://{}/".format(server)) 
Example 3
Project: openISP   Author: cruxopen   File: nlm.py    License: MIT License 6 votes vote down vote up
def execute(self):
        img_pad = self.padding()
        img_pad = img_pad.astype(np.uint16)
        raw_h = self.img.shape[0]
        raw_w = self.img.shape[1]
        nlm_img = np.empty((raw_h, raw_w), np.uint16)
        kernel = np.ones((2*self.ds+1, 2*self.ds+1)) / pow(2*self.ds+1, 2)
        for y in range(img_pad.shape[0] - 2 * self.Ds):
            for x in range(img_pad.shape[1] - 2 * self.Ds):
                center_y = y + self.Ds
                center_x = x + self.Ds
                sweight, average, wmax = self.calWeights(img_pad, kernel, center_y, center_x)
                average = average + wmax * img_pad[center_y, center_x]
                sweight = sweight + wmax
                nlm_img[y,x] = average / sweight
        self.img = nlm_img
        return self.clipping() 
Example 4
Project: openISP   Author: cruxopen   File: aaf.py    License: MIT License 6 votes vote down vote up
def execute(self):
        img_pad = self.padding()
        raw_h = self.img.shape[0]
        raw_w = self.img.shape[1]
        aaf_img = np.empty((raw_h, raw_w), np.uint16)
        for y in range(img_pad.shape[0] - 4):
            for x in range(img_pad.shape[1] - 4):
                p0 = img_pad[y + 2, x + 2]
                p1 = img_pad[y, x]
                p2 = img_pad[y, x + 2]
                p3 = img_pad[y, x + 4]
                p4 = img_pad[y + 2, x]
                p5 = img_pad[y + 2, x + 4]
                p6 = img_pad[y + 4, x]
                p7 = img_pad[y + 4, x + 2]
                p8 = img_pad[y + 4, x + 4]
                aaf_img[y, x] = (p0 * 8 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8) / 16
        self.img = aaf_img
        return self.img 
Example 5
Project: me-ica   Author: ME-ICA   File: test_ecat.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_subheader(self):
        assert_equal(self.subhdr.get_shape() , (10,10,3))
        assert_equal(self.subhdr.get_nframes() , 1)
        assert_equal(self.subhdr.get_nframes(),
                     len(self.subhdr.subheaders))
        assert_equal(self.subhdr._check_affines(), True)
        assert_array_almost_equal(np.diag(self.subhdr.get_frame_affine()),
                                  np.array([ 2.20241979, 2.20241979, 3.125,  1.]))
        assert_equal(self.subhdr.get_zooms()[0], 2.20241978764534)
        assert_equal(self.subhdr.get_zooms()[2], 3.125)
        assert_equal(self.subhdr._get_data_dtype(0),np.uint16)
        #assert_equal(self.subhdr._get_frame_offset(), 1024)
        assert_equal(self.subhdr._get_frame_offset(), 1536)
        dat = self.subhdr.raw_data_from_fileobj()
        assert_equal(dat.shape, self.subhdr.get_shape())
        scale_factor = self.subhdr.subheaders[0]['scale_factor']
        assert_equal(self.subhdr.subheaders[0]['scale_factor'].item(),1.0)
        ecat_calib_factor = self.hdr['ecat_calibration_factor']
        assert_equal(ecat_calib_factor, 25007614.0) 
Example 6
Project: me-ica   Author: ME-ICA   File: test_casting.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_able_int_type():
    # The integer type cabable of containing values
    for vals, exp_out in (
        ([0, 1], np.uint8),
        ([0, 255], np.uint8),
        ([-1, 1], np.int8),
        ([0, 256], np.uint16),
        ([-1, 128], np.int16),
        ([0.1, 1], None),
        ([0, 2**16], np.uint32),
        ([-1, 2**15], np.int32),
        ([0, 2**32], np.uint64),
        ([-1, 2**31], np.int64),
        ([-1, 2**64-1], None),
        ([0, 2**64-1], np.uint64),
        ([0, 2**64], None)):
        assert_equal(able_int_type(vals), exp_out) 
Example 7
Project: me-ica   Author: ME-ICA   File: test_utils.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_can_cast():
    tests = ((np.float32, np.float32, True, True, True),
             (np.float64, np.float32, True, True, True),
             (np.complex128, np.float32, False, False, False),
             (np.float32, np.complex128, True, True, True),
             (np.float32, np.uint8, False, True, True),
             (np.uint32, np.complex128, True, True, True),
             (np.int64, np.float32, True, True, True),
             (np.complex128, np.int16, False, False, False),
             (np.float32, np.int16, False, True, True),
             (np.uint8, np.int16, True, True, True),
             (np.uint16, np.int16, False, True, True),
             (np.int16, np.uint16, False, False, True),
             (np.int8, np.uint16, False, False, True),
             (np.uint16, np.uint8, False, True, True),
             )
    for intype, outtype, def_res, scale_res, all_res in tests:
        assert_equal(def_res, can_cast(intype, outtype))
        assert_equal(scale_res, can_cast(intype, outtype, False, True))
        assert_equal(all_res, can_cast(intype, outtype, True, True)) 
Example 8
Project: radiometric_normalization   Author: planetlabs   File: normalize.py    License: Apache License 2.0 6 votes vote down vote up
def apply_using_lut(input_band, transformation):
    '''Applies a linear transformation to an array using a look up table.
    This creates a uint16 array as the output and clips the output band
    to the range of a uint16.

    :param array input_band: A 2D array representing the image data of the
        a single band
    :param LinearTransformation transformation: A LinearTransformation
        (gain and offset)

    :returns: A 2D array of of the input_band with the transformation applied
    '''
    logging.info('Normalize: Applying linear transformation to band (uint16)')

    def _apply_lut(band, lut):
        '''Changes band intensity values based on intensity look up table (lut)
        '''
        if lut.dtype != band.dtype:
            raise Exception(
                'Band ({}) and lut ({}) must be the same data type.').format(
                band.dtype, lut.dtype)
        return numpy.take(lut, band, mode='clip')

    lut = _linear_transformation_to_lut(transformation)
    return _apply_lut(input_band, lut) 
Example 9
Project: radiometric_normalization   Author: planetlabs   File: time_stack.py    License: Apache License 2.0 6 votes vote down vote up
def _uniform_weight_alpha(sum_masked_arrays, output_datatype):
    '''Calculates the cumulative mask of a list of masked array

    Input:
        sum_masked_arrays (list of numpy masked arrays): The list of
            masked arrays to find the cumulative mask of, each element
            represents one band.
            (sums_masked_array.mask has a 1 for a no data pixel and
            a 0 otherwise)
        output_datatype (numpy datatype): The output datatype

    Output:
        output_alpha (numpy uint16 array): The output mask
            (0 for a no data pixel, uint16 max value otherwise)
    '''

    output_alpha = numpy.ones(sum_masked_arrays[0].shape)
    for band_sum_masked_array in sum_masked_arrays:
        output_alpha[numpy.nonzero(band_sum_masked_array.mask == 1)] = 0

    output_alpha = output_alpha.astype(output_datatype) * \
        numpy.iinfo(output_datatype).max

    return output_alpha 
Example 10
Project: radiometric_normalization   Author: planetlabs   File: gimage_tests.py    License: Apache License 2.0 6 votes vote down vote up
def test_save_with_compress(self):
        output_file = 'test_save_with_compress.tif'
        test_band = numpy.array([[5, 2, 2], [1, 6, 8]], dtype=numpy.uint16)
        test_alpha = numpy.array([[0, 0, 0], [1, 1, 1]], dtype=numpy.bool)
        test_gimage = gimage.GImage([test_band, test_band, test_band],
                                    test_alpha, self.metadata)
        gimage.save(test_gimage, output_file, compress=True)

        result_gimg = gimage.load(output_file)
        numpy.testing.assert_array_equal(result_gimg.bands[0], test_band)
        numpy.testing.assert_array_equal(result_gimg.bands[1], test_band)
        numpy.testing.assert_array_equal(result_gimg.bands[2], test_band)
        numpy.testing.assert_array_equal(result_gimg.alpha, test_alpha)
        self.assertEqual(result_gimg.metadata, self.metadata)

        os.unlink(output_file) 
Example 11
Project: simnibs   Author: simnibs   File: hmutils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def format_time(running_time):
    """Format time in seconds as hours:minutes:seconds.
    
    PARAMETERS
    ----------
    running_time : float
        Time in seconds.
    
    RETURNS
    ----------
    running_time : str
        The time formatted as hours:minutes:seconds.
    """
    hrs = np.uint16(np.floor(running_time/(60.**2)))
    mts = np.uint16(np.floor(running_time/60.-hrs*60))
    sec = np.uint16(np.round(running_time-hrs*60.**2-mts*60.))

    return "{:02d}:{:02d}:{:02d}".format(hrs,mts,sec) 
Example 12
Project: exposure   Author: yuanming-hu   File: util.py    License: MIT License 6 votes vote down vote up
def read_tiff16(fn):
  import tifffile
  import numpy as np
  img = tifffile.imread(fn)
  if img.dtype == np.uint8:
    depth = 8
  elif img.dtype == np.uint16:
    depth = 16
  else:
    print("Warning: unsupported data type {}. Assuming 16-bit.", img.dtype)
    depth = 16

  return (img * (1.0 / (2**depth - 1))).astype(np.float32) 
Example 13
Project: modelforge   Author: src-d   File: model.py    License: Apache License 2.0 6 votes vote down vote up
def squeeze_bits(arr: numpy.ndarray) -> numpy.ndarray:
    """Return a copy of an integer numpy array with the minimum bitness."""
    assert arr.dtype.kind in ("i", "u")
    if arr.size == 0:
        return arr
    if arr.dtype.kind == "i":
        assert arr.min() >= 0
    mlbl = int(arr.max()).bit_length()
    if mlbl <= 8:
        dtype = numpy.uint8
    elif mlbl <= 16:
        dtype = numpy.uint16
    elif mlbl <= 32:
        dtype = numpy.uint32
    else:
        dtype = numpy.uint64
    return arr.astype(dtype) 
Example 14
Project: yatsm   Author: ceholden   File: longtermmean.py    License: MIT License 6 votes vote down vote up
def group_years(years, interval=3):
    """ Return integers representing sequential groupings of years

    Note: years specified must be sorted

    Args:
        years (np.ndarray): the year corresponding to each EVI value
        interval (int, optional): number of years to group together
            (default: 3)

    Returns:
        np.ndarray: integers representing sequential year groupings

    """
    n_groups = math.ceil((years.max() - years.min()) / interval)
    if n_groups <= 1:
        return np.zeros_like(years, dtype=np.uint16)
    splits = np.array_split(np.arange(years.min(), years.max() + 1), n_groups)

    groups = np.zeros_like(years, dtype=np.uint16)
    for i, s in enumerate(splits):
        groups[np.in1d(years, s)] = i

    return groups 
Example 15
Project: yatsm   Author: ceholden   File: longtermmean.py    License: MIT License 6 votes vote down vote up
def ordinal2yeardoy(ordinal):
    """ Convert ordinal dates to two arrays of year and doy

    Args:
        ordinal (np.ndarray): ordinal dates

    Returns:
        np.ndarray: nobs x 2 np.ndarray containing the year and DOY for each
            ordinal date

    """
    _date = [dt.fromordinal(_d) for _d in ordinal]
    yeardoy = np.empty((ordinal.size, 2), dtype=np.uint16)
    yeardoy[:, 0] = np.array([int(_d.strftime('%Y')) for _d in _date])
    yeardoy[:, 1] = np.array([int(_d.strftime('%j')) for _d in _date])

    return yeardoy 
Example 16
Project: recruit   Author: Frank-qlu   File: test_ctypeslib.py    License: Apache License 2.0 6 votes vote down vote up
def test_padded_union(self):
        dt = np.dtype(dict(
            names=['a', 'b'],
            offsets=[0, 0],
            formats=[np.uint16, np.uint32],
            itemsize=5,
        ))

        ct = np.ctypeslib.as_ctypes_type(dt)
        assert_(issubclass(ct, ctypes.Union))
        assert_equal(ctypes.sizeof(ct), dt.itemsize)
        assert_equal(ct._fields_, [
            ('a', ctypes.c_uint16),
            ('b', ctypes.c_uint32),
            ('', ctypes.c_char * 5),  # padding
        ]) 
Example 17
Project: recruit   Author: Frank-qlu   File: test_function_base.py    License: Apache License 2.0 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int8, np.uint8, np.int16, np.uint16, np.int32,
                      np.uint32, np.float32, np.float64, np.complex64,
                      np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)

            tgt = np.array([1, 3, 13, 24, 30, 35, 39], ctype)
            assert_array_equal(np.cumsum(a, axis=0), tgt)

            tgt = np.array(
                [[1, 2, 3, 4], [6, 8, 10, 13], [16, 11, 14, 18]], ctype)
            assert_array_equal(np.cumsum(a2, axis=0), tgt)

            tgt = np.array(
                [[1, 3, 6, 10], [5, 11, 18, 27], [10, 13, 17, 22]], ctype)
            assert_array_equal(np.cumsum(a2, axis=1), tgt) 
Example 18
Project: recruit   Author: Frank-qlu   File: test_function_base.py    License: Apache License 2.0 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                assert_raises(ArithmeticError, np.cumprod, a)
                assert_raises(ArithmeticError, np.cumprod, a2, 1)
                assert_raises(ArithmeticError, np.cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis=-1),
                                   np.array([1, 2, 20, 220,
                                             1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                                   np.array([[1, 2, 3, 4],
                                             [5, 12, 21, 36],
                                             [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis=-1),
                                   np.array([[1, 2, 6, 24],
                                             [5, 30, 210, 1890],
                                             [10, 30, 120, 600]], ctype)) 
Example 19
Project: recruit   Author: Frank-qlu   File: test_half.py    License: Apache License 2.0 6 votes vote down vote up
def test_half_conversion_denormal_round_even(self, float_t, uint_t, bits):
        # Test specifically that all bits are considered when deciding
        # whether round to even should occur (i.e. no bits are lost at the
        # end. Compare also gh-12721. The most bits can get lost for the
        # smallest denormal:
        smallest_value = np.uint16(1).view(np.float16).astype(float_t)
        assert smallest_value == 2**-24

        # Will be rounded to zero based on round to even rule:
        rounded_to_zero = smallest_value / float_t(2)
        assert rounded_to_zero.astype(np.float16) == 0

        # The significand will be all 0 for the float_t, test that we do not
        # lose the lower ones of these:
        for i in range(bits):
            # slightly increasing the value should make it round up:
            larger_pattern = rounded_to_zero.view(uint_t) | uint_t(1 << i)
            larger_value = larger_pattern.view(float_t)
            assert larger_value.astype(np.float16) == smallest_value 
Example 20
Project: recruit   Author: Frank-qlu   File: test_half.py    License: Apache License 2.0 6 votes vote down vote up
def test_half_values(self):
        """Confirms a small number of known half values"""
        a = np.array([1.0, -1.0,
                      2.0, -2.0,
                      0.0999755859375, 0.333251953125,  # 1/10, 1/3
                      65504, -65504,           # Maximum magnitude
                      2.0**(-14), -2.0**(-14),  # Minimum normal
                      2.0**(-24), -2.0**(-24),  # Minimum subnormal
                      0, -1/1e1000,            # Signed zeros
                      np.inf, -np.inf])
        b = np.array([0x3c00, 0xbc00,
                      0x4000, 0xc000,
                      0x2e66, 0x3555,
                      0x7bff, 0xfbff,
                      0x0400, 0x8400,
                      0x0001, 0x8001,
                      0x0000, 0x8000,
                      0x7c00, 0xfc00], dtype=uint16)
        b.dtype = float16
        assert_equal(a, b) 
Example 21
Project: vergeml   Author: mme   File: env.py    License: MIT License 5 votes vote down vote up
def _toscalar(v):
    if isinstance(v, (np.float16, np.float32, np.float64,
                      np.uint8, np.uint16, np.uint32, np.uint64,
                      np.int8, np.int16, np.int32, np.int64)):
        return np.asscalar(v)
    else:
        return v 
Example 22
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: kimotion.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        d = self._ws_thread.get_frame()
        d = d.reshape(WS_FRAME_HEIGHT, WS_FRAME_WIDTH)
        if self.mirror:
            d = np.fliplr(d)

        d = rebin(d, (self.height, self.width)).astype(np.uint16)

        self.shader.render(d) 
Example 23
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: pascal_voc.py    License: Apache License 2.0 5 votes vote down vote up
def _load_annotation(self, index):
        # store original annotation as orig_objs
        height, width, orig_objs = self._parse_voc_anno(self._image_anno_tmpl.format(index))

        # filter difficult objects
        if not self._config['use_diff']:
            non_diff_objs = [obj for obj in orig_objs if obj['difficult'] == 0]
            objs = non_diff_objs
        else:
            objs = orig_objs
        num_objs = len(objs)

        boxes = np.zeros((num_objs, 4), dtype=np.uint16)
        gt_classes = np.zeros((num_objs,), dtype=np.int32)
        # Load object bounding boxes into a data frame.
        for ix, obj in enumerate(objs):
            # Make pixel indexes 0-based
            x1 = obj['bbox'][0] - 1
            y1 = obj['bbox'][1] - 1
            x2 = obj['bbox'][2] - 1
            y2 = obj['bbox'][3] - 1
            cls = self._class_to_ind[obj['name'].lower().strip()]
            boxes[ix, :] = [x1, y1, x2, y2]
            gt_classes[ix] = cls

        roi_rec = {'index': index,
                   'objs': orig_objs,
                   'image': self._image_file_tmpl.format(index),
                   'height': height,
                   'width': width,
                   'boxes': boxes,
                   'gt_classes': gt_classes,
                   'flipped': False}
        return roi_rec 
Example 24
Project: PolarSeg   Author: edwardzhou130   File: dataset.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def nb_process_label(processed_label,sorted_label_voxel_pair):
    label_size = 256
    counter = np.zeros((label_size,),dtype = np.uint16)
    counter[sorted_label_voxel_pair[0,3]] = 1
    cur_sear_ind = sorted_label_voxel_pair[0,:3]
    for i in range(1,sorted_label_voxel_pair.shape[0]):
        cur_ind = sorted_label_voxel_pair[i,:3]
        if not np.all(np.equal(cur_ind,cur_sear_ind)):
            processed_label[cur_sear_ind[0],cur_sear_ind[1],cur_sear_ind[2]] = np.argmax(counter)
            counter = np.zeros((label_size,),dtype = np.uint16)
            cur_sear_ind = cur_ind
        counter[sorted_label_voxel_pair[i,3]] += 1
    processed_label[cur_sear_ind[0],cur_sear_ind[1],cur_sear_ind[2]] = np.argmax(counter)
    return processed_label 
Example 25
Project: cascade-rcnn_Pytorch   Author: guoruoqian   File: imagenet.py    License: MIT License 5 votes vote down vote up
def _load_imagenet_annotation(self, index):
        """
        Load image and bounding boxes info from txt files of imagenet.
        """
        filename = os.path.join(self._data_path, 'Annotations', self._image_set, index + '.xml')

        # print 'Loading: {}'.format(filename)
        def get_data_from_tag(node, tag):
            return node.getElementsByTagName(tag)[0].childNodes[0].data

        with open(filename) as f:
            data = minidom.parseString(f.read())

        objs = data.getElementsByTagName('object')
        num_objs = len(objs)

        boxes = np.zeros((num_objs, 4), dtype=np.uint16)
        gt_classes = np.zeros((num_objs), dtype=np.int32)
        overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32)

        # Load object bounding boxes into a data frame.
        for ix, obj in enumerate(objs):
            x1 = float(get_data_from_tag(obj, 'xmin'))
            y1 = float(get_data_from_tag(obj, 'ymin'))
            x2 = float(get_data_from_tag(obj, 'xmax'))
            y2 = float(get_data_from_tag(obj, 'ymax'))
            cls = self._wnid_to_ind[
                    str(get_data_from_tag(obj, "name")).lower().strip()]
            boxes[ix, :] = [x1, y1, x2, y2]
            gt_classes[ix] = cls
            overlaps[ix, cls] = 1.0

        overlaps = scipy.sparse.csr_matrix(overlaps)

        return {'boxes' : boxes,
                'gt_classes': gt_classes,
                'gt_overlaps' : overlaps,
                'flipped' : False} 
Example 26
Project: openISP   Author: cruxopen   File: dpc.py    License: MIT License 5 votes vote down vote up
def execute(self):
        img_pad = self.padding()
        raw_h = self.img.shape[0]
        raw_w = self.img.shape[1]
        dpc_img = np.empty((raw_h, raw_w), np.uint16)
        for y in range(img_pad.shape[0] - 4):
            for x in range(img_pad.shape[1] - 4):
                p0 = img_pad[y + 2, x + 2]
                p1 = img_pad[y, x]
                p2 = img_pad[y, x + 2]
                p3 = img_pad[y, x + 4]
                p4 = img_pad[y + 2, x]
                p5 = img_pad[y + 2, x + 4]
                p6 = img_pad[y + 4, x]
                p7 = img_pad[y + 4, x + 2]
                p8 = img_pad[y + 4, x + 4]
                if (abs(p1 - p0) > self.thres) and (abs(p2 - p0) > self.thres) and (abs(p3 - p0) > self.thres) \
                        and (abs(p4 - p0) > self.thres) and (abs(p5 - p0) > self.thres) and (abs(p6 - p0) > self.thres) \
                        and (abs(p7 - p0) > self.thres) and (abs(p8 - p0) > self.thres):
                    if self.mode == 'mean':
                        p0 = (p2 + p4 + p5 + p7) / 4
                    elif self.mode == 'gradient':
                        dv = abs(2 * p0 - p2 - p7)
                        dh = abs(2 * p0 - p4 - p5)
                        ddl = abs(2 * p0 - p1 - p8)
                        ddr = abs(2 * p0 - p3 - p6)
                        if (min(dv, dh, ddl, ddr) == dv):
                            p0 = (p2 + p7 + 1) / 2
                        elif (min(dv, dh, ddl, ddr) == dh):
                            p0 = (p4 + p5 + 1) / 2
                        elif (min(dv, dh, ddl, ddr) == ddl):
                            p0 = (p1 + p8 + 1) / 2
                        else:
                            p0 = (p3 + p6 + 1) / 2
                dpc_img[y, x] = p0
        self.img = dpc_img
        return self.clipping() 
Example 27
Project: L3C-PyTorch   Author: fab-jul   File: bitcoding.py    License: GNU General Public License v3.0 5 votes vote down vote up
def write_shape(shape, fout):
    """
    Write tuple (C,H,W) to file, given shape 1CHW.
    :return number of bytes written
    """
    assert len(shape) == 4 and shape[0] == 1, shape
    shape = shape[1:]
    assert shape[0] < 2**8,  shape
    assert shape[1] < 2**16, shape
    assert shape[2] < 2**16, shape
    assert len(shape) == 3,  shape
    write_bytes(fout, [np.uint8, np.uint16, np.uint16], shape)
    return 5 
Example 28
Project: L3C-PyTorch   Author: fab-jul   File: bitcoding.py    License: GNU General Public License v3.0 5 votes vote down vote up
def read_shapes(fin):
    return tuple(map(int, read_bytes(fin, [np.uint8, np.uint16, np.uint16]))) 
Example 29
Project: L3C-PyTorch   Author: fab-jul   File: bitcoding.py    License: GNU General Public License v3.0 5 votes vote down vote up
def write_padding_tuple(padding_tuple, fout):
    assert len(padding_tuple) == 4
    write_bytes(fout,
                [np.uint16, np.uint16, np.uint16, np.uint16],
                padding_tuple) 
Example 30
Project: L3C-PyTorch   Author: fab-jul   File: bitcoding.py    License: GNU General Public License v3.0 5 votes vote down vote up
def read_padding_tuple(fin):
    return tuple(map(int, read_bytes(fin, [np.uint16, np.uint16, np.uint16, np.uint16])))