Python numpy.bitwise_xor() 使用实例

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

def find_uglies():
    '''image-net gives a default image when it's real one is not available,
        this is to remove them
    '''
    for file_type in ['neg']:
        for img in os.listdir(file_type):
            for ugly in os.listdir('uglies'):
                try:
                    current_image_path = str(file_type) + '/' + str(img)
                    ugly = cv2.imread('uglies/' + str(ugly))
                    question = cv2.imread(current_image_path)

                    if ugly.shape == question.shape and not (np.bitwise_xor(ugly, question).any()):
                        print "girl you ugly"
                        os.remove(current_image_path)
                except:
                    print "error" 

Example 2

def main():
    if len(sys.argv) != 4:
        usage()
        exit(1)

    img_in = sys.argv[1]
    key_in = sys.argv[2]
    img_out = sys.argv[3]

    img = Image.open(img_in).convert("RGB")
    key = Image.open(key_in).convert("RGB")
    pimg = img.load()
    pkey = key.load()

    width, height = img.size

    for i in range(width):
        for j in range(height):
            imga = pimg[i, j]
            keya = pkey[i, j]
            encp = numpy.bitwise_xor(imga, keya)
            pimg[i,j] = tuple(encp)
    
    img.save(img_out) 

Example 3

def main():
    if len(sys.argv) != 4:
        usage()
        exit(1)

    img_in = sys.argv[1]
    key_in = sys.argv[2]
    img_out = sys.argv[3]

    img = Image.open(img_in).convert("RGB")
    key = Image.open(key_in).convert("RGB")
    pimg = img.load()
    pkey = key.load()

    width, height = img.size

    for i in range(width):
        for j in range(height):
            imga = pimg[i, j]
            keya = pkey[i, j]
            encp = numpy.bitwise_xor(imga, keya)
            pimg[i,j] = tuple(encp)
    
    img.save(img_out) 

Example 4

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 5

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 6

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 7

def test_values(self):
        for dt in self.bitwise_types:
            zeros = np.array([0], dtype=dt)
            ones = np.array([-1], dtype=dt)
            msg = "dt = '%s'" % dt.char

            assert_equal(np.bitwise_not(zeros), ones, err_msg=msg)
            assert_equal(np.bitwise_not(ones), zeros, err_msg=msg)

            assert_equal(np.bitwise_or(zeros, zeros), zeros, err_msg=msg)
            assert_equal(np.bitwise_or(zeros, ones), ones, err_msg=msg)
            assert_equal(np.bitwise_or(ones, zeros), ones, err_msg=msg)
            assert_equal(np.bitwise_or(ones, ones), ones, err_msg=msg)

            assert_equal(np.bitwise_xor(zeros, zeros), zeros, err_msg=msg)
            assert_equal(np.bitwise_xor(zeros, ones), ones, err_msg=msg)
            assert_equal(np.bitwise_xor(ones, zeros), ones, err_msg=msg)
            assert_equal(np.bitwise_xor(ones, ones), zeros, err_msg=msg)

            assert_equal(np.bitwise_and(zeros, zeros), zeros, err_msg=msg)
            assert_equal(np.bitwise_and(zeros, ones), zeros, err_msg=msg)
            assert_equal(np.bitwise_and(ones, zeros), zeros, err_msg=msg)
            assert_equal(np.bitwise_and(ones, ones), ones, err_msg=msg) 

Example 8

def set_ufunc(self, scalar_op):
        # This is probably a speed up of the implementation
        if isinstance(scalar_op, theano.scalar.basic.Add):
            self.ufunc = numpy.add
        elif isinstance(scalar_op, theano.scalar.basic.Mul):
            self.ufunc = numpy.multiply
        elif isinstance(scalar_op, theano.scalar.basic.Maximum):
            self.ufunc = numpy.maximum
        elif isinstance(scalar_op, theano.scalar.basic.Minimum):
            self.ufunc = numpy.minimum
        elif isinstance(scalar_op, theano.scalar.basic.AND):
            self.ufunc = numpy.bitwise_and
        elif isinstance(scalar_op, theano.scalar.basic.OR):
            self.ufunc = numpy.bitwise_or
        elif isinstance(scalar_op, theano.scalar.basic.XOR):
            self.ufunc = numpy.bitwise_xor
        else:
            self.ufunc = numpy.frompyfunc(scalar_op.impl, 2, 1) 

Example 9

def test_centre(self):
        # Request new centre below current centre
        new_centre = (100, 100)

        # Load image for testing.
        image = cv2.imread(os.path.join(self.path_to_test_data, 'pad_test_input.png'))
        image = cv2.resize(image, (200, 200))

        # Check image was loaded correctly
        if image is None:
            raise TypeError

        # Pad Image.
        modified_image = camera_utils.pad_image(image, new_centre)

        # Compare images
        self.assertTrue(not (np.bitwise_xor(modified_image, image).any())) 

Example 10

def pad_test(self, filename_without_extension, new_centre):
        # Load image for testing.
        image = cv2.imread(os.path.join(self.path_to_test_data, 'pad_test_input.png'))
        image = cv2.resize(image, (200, 200))

        # Check image was loaded correctly
        if image is None:
            raise TypeError

        # Pad Image.
        modified_image = camera_utils.pad_image(image, new_centre)

        # This has to be done with png.
        expected_results_file = os.path.join(self.path_to_test_data, filename_without_extension + '_expected.png')
        # self._overwrite_expected_results_file(expected_results_file, modified_image)

        # Load expected image
        expected_image = cv2.imread(expected_results_file)

        # Compare images
        self.assertTrue(not(np.bitwise_xor(modified_image, expected_image).any())) 

Example 11

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 12

def test_truth_table_bitwise(self):
        arg1 = [False, False, True, True]
        arg2 = [False, True, False, True]

        out = [False, True, True, True]
        assert_equal(np.bitwise_or(arg1, arg2), out)

        out = [False, False, False, True]
        assert_equal(np.bitwise_and(arg1, arg2), out)

        out = [False, True, True, False]
        assert_equal(np.bitwise_xor(arg1, arg2), out) 

Example 13

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 14

def __xor__(self, other):
        return bitwise_xor(self, other) 

Example 15

def __ixor__(self, other):
        return bitwise_xor(self, other, self) 

Example 16

def __rxor__(self, other):
        return bitwise_xor(other, self) 

Example 17

def test_truth_table_bitwise(self):
        arg1 = [False, False, True, True]
        arg2 = [False, True, False, True]

        out = [False, True, True, True]
        assert_equal(np.bitwise_or(arg1, arg2), out)

        out = [False, False, False, True]
        assert_equal(np.bitwise_and(arg1, arg2), out)

        out = [False, True, True, False]
        assert_equal(np.bitwise_xor(arg1, arg2), out) 

Example 18

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 19

def __ixor__(self, other):
            np.bitwise_xor(self, other, out=self)
            return self 

Example 20

def test_truth_table_bitwise(self):
        arg1 = [False, False, True, True]
        arg2 = [False, True, False, True]

        out = [False, True, True, True]
        assert_equal(np.bitwise_or(arg1, arg2), out)

        out = [False, False, False, True]
        assert_equal(np.bitwise_and(arg1, arg2), out)

        out = [False, True, True, False]
        assert_equal(np.bitwise_xor(arg1, arg2), out) 

Example 21

def test_truth_table_bitwise(self):
        arg1 = [False, False, True, True]
        arg2 = [False, True, False, True]

        out = [False, True, True, True]
        assert_equal(np.bitwise_or(arg1, arg2), out)

        out = [False, False, False, True]
        assert_equal(np.bitwise_and(arg1, arg2), out)

        out = [False, True, True, False]
        assert_equal(np.bitwise_xor(arg1, arg2), out) 

Example 22

def cipherPayload(self, aesWithKey, frmPayloadStr, updown, devAddr, seqCnt):
        '''
        aesWithKey: a cipher object from CryptoPlus
        frmPayloadStr: | FRMPayload |
        updown: 0 for UP_LINK and 1 for DOWN_LINK
        devAddr (uint32): 4-byte device address
        seqCnt (uint32): frame count

        LoRaWAN Specification v1.0 Ch4.3.3.1
        '''
        paddedPaylod = self.padToBlockSize(frmPayloadStr)
        k = int(math.ceil(len(frmPayloadStr) / 16.0))
        A = bytearray([1, 0, 0, 0, 0, updown, devAddr & 0xFF,
                       (devAddr >> 8) & 0xFF,
                       (devAddr >> 16) & 0xFF,
                       (devAddr >> 24) & 0xFF,
                       seqCnt & 0xFF,
                       (seqCnt >> 8) & 0xFF,
                       (seqCnt >> 16) & 0xFF,
                       (seqCnt >> 24) & 0xFF,
                       0, 0])

        S = ''
        aesWithKey.final() # clear the cipher's cache
        for i in xrange(1, k+1):
            A[15] = i
            S += aesWithKey.encrypt(str(A))
        aesWithKey.final() # clear the cipher's cache
        
        dtype = numpy.dtype('<Q8')
        ciphered = numpy.bitwise_xor(numpy.fromstring(paddedPaylod,dtype=dtype),
                                   numpy.fromstring(S,dtype=dtype)).tostring()
        return ciphered[:len(frmPayloadStr)] 

Example 23

def test_truth_table_bitwise(self):
        arg1 = [False, False, True, True]
        arg2 = [False, True, False, True]

        out = [False, True, True, True]
        assert_equal(np.bitwise_or(arg1, arg2), out)

        out = [False, False, False, True]
        assert_equal(np.bitwise_and(arg1, arg2), out)

        out = [False, True, True, False]
        assert_equal(np.bitwise_xor(arg1, arg2), out) 

Example 24

def get_synthetic_clusters_dataset(n_clusters = 4, n_dims = 20, n_training = 1000, n_test = 200,
        sparsity = 0.5, flip_noise = 0.1, seed = 3425, dtype = 'float32'):
    """
    A dataset consisting of clustered binary data with "bit-flip" noise, and the corresponding cluster labels.
    This should be trivially solvable by any classifier, and serves as a basic test of whether your classifier is
    completely broken or not.

    :param n_clusters:
    :param n_dims:
    :param n_samples_training:
    :param n_samples_test:
    :param sparsity:
    :param flip_noise:
    :param seed:
    :return:
    """

    rng = np.random.RandomState(seed)
    labels = rng.randint(n_clusters, size = n_training+n_test)  # (n_samples, )
    centers = rng.rand(n_clusters, n_dims) < sparsity  # (n_samples, n_dims)
    input_data = centers[labels]
    input_data = np.bitwise_xor(input_data, rng.rand(*input_data.shape) < flip_noise).astype(dtype)

    return DataSet(
        training_set = DataCollection(input_data[:n_training], labels[:n_training]),
        test_set = DataCollection(input_data[n_training:], labels[n_training:]),
        name = 'Synthetic Clusters Dataset'
        ) 

Example 25

def test_truth_table_bitwise(self):
        arg1 = [False, False, True, True]
        arg2 = [False, True, False, True]

        out = [False, True, True, True]
        assert_equal(np.bitwise_or(arg1, arg2), out)

        out = [False, False, False, True]
        assert_equal(np.bitwise_and(arg1, arg2), out)

        out = [False, True, True, False]
        assert_equal(np.bitwise_xor(arg1, arg2), out) 

Example 26

def test_types(self):
        for dt in self.bitwise_types:
            zeros = np.array([0], dtype=dt)
            ones = np.array([-1], dtype=dt)
            msg = "dt = '%s'" % dt.char

            assert_(np.bitwise_not(zeros).dtype == dt, msg)
            assert_(np.bitwise_or(zeros, zeros).dtype == dt, msg)
            assert_(np.bitwise_xor(zeros, zeros).dtype == dt, msg)
            assert_(np.bitwise_and(zeros, zeros).dtype == dt, msg) 

Example 27

def test_identity(self):
        assert_(np.bitwise_or.identity == 0, 'bitwise_or')
        assert_(np.bitwise_xor.identity == 0, 'bitwise_xor')
        assert_(np.bitwise_and.identity == -1, 'bitwise_and') 

Example 28

def test_reduction(self):
        binary_funcs = (np.bitwise_or, np.bitwise_xor, np.bitwise_and)

        for dt in self.bitwise_types:
            zeros = np.array([0], dtype=dt)
            ones = np.array([-1], dtype=dt)
            for f in binary_funcs:
                msg = "dt: '%s', f: '%s'" % (dt, f)
                assert_equal(f.reduce(zeros), zeros, err_msg=msg)
                assert_equal(f.reduce(ones), ones, err_msg=msg)

        # Test empty reduction, no object dtype
        for dt in self.bitwise_types[:-1]:
            # No object array types
            empty = np.array([], dtype=dt)
            for f in binary_funcs:
                msg = "dt: '%s', f: '%s'" % (dt, f)
                tgt = np.array(f.identity, dtype=dt)
                res = f.reduce(empty)
                assert_equal(res, tgt, err_msg=msg)
                assert_(res.dtype == tgt.dtype, msg)

        # Empty object arrays use the identity.  Note that the types may
        # differ, the actual type used is determined by the assign_identity
        # function and is not the same as the type returned by the identity
        # method.
        for f in binary_funcs:
            msg = "dt: '%s'" % (f,)
            empty = np.array([], dtype=object)
            tgt = f.identity
            res = f.reduce(empty)
            assert_equal(res, tgt, err_msg=msg)

        # Non-empty object arrays do not use the identity
        for f in binary_funcs:
            msg = "dt: '%s'" % (f,)
            btype = np.array([True], dtype=object)
            assert_(type(f.reduce(btype)) is bool, msg) 

Example 29

def test_truth_table_bitwise(self):
        arg1 = [False, False, True, True]
        arg2 = [False, True, False, True]

        out = [False, True, True, True]
        assert_equal(np.bitwise_or(arg1, arg2), out)

        out = [False, False, False, True]
        assert_equal(np.bitwise_and(arg1, arg2), out)

        out = [False, True, True, False]
        assert_equal(np.bitwise_xor(arg1, arg2), out) 

Example 30

def find_uglies():
    for file_type in ['Negative']:
        for img in os.listdir(file_type):
            for ugly in os.listdir('uglies'):
                try:
                    current_image_path=str(file_type)+'/'+str(img)
                    ugly=cv2.imread('uglies/'+str(ugly))
                    question=cv2.imread(current_image_path)
                    if ugly.shape==question.shape and not (np.bitwise_xor(ugly,question).any()):
                        os.remove(current_image_path)
                        print ('Ohyeahh')
                except Exception as e:
                    print (str(e)) 
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注