Tensorflow2(keras)-图像预处理操作(tf.EagerTensor和tf.Tensor)

 在tensorflow.keras训练中,如果需要对图像进行预处理操作(数据增强操作),发现很多opencv方法用不了,不能对图像进行直接处理,

如果使用np.array(x),就会报错:

 NotImplementedError: Cannot convert a symbolic Tensor  to a numpy array 

如果使用x.numpy(),就会报错:

AttributeError: 'Tensor' object has no attribute 'numpy'

所以需要单独加载预处理方法,tf.py_function(aug_image_func, [image], tf.float32),将处理操作放到aug_image_func中,就可以直接image.numpy()了,不然也会报错哦!

def preprocess_image(filename):
        # print(filename)
        img = tf.io.read_file(filename)
        img = tf.cond(
            tf.image.is_jpeg(img),
            lambda: tf.image.decode_jpeg(img, channels=0),
            lambda: tf.image.decode_bmp(img, channels=0))
        img = tf.image.convert_image_dtype(img, tf.float32)
        img = random_aug_image(img,zoom_type,(32,100)) 
        # img = tf.image.resize(img, (32, 100),method= tf.image.ResizeMethod.BICUBIC)
        # img = tf.image.random_brightness(img, max_delta=0.4)
        # tf.print(tf.shape(img))
        return img
def random_aug_image(image,zoom_type,img_size):
   
    def aug_image_func(image):
        # print(image.shape)
        image=image.numpy()*255
        if len(image.shape)==3:
            image = image.mean(axis=2).astype(np.float32)
        image=cv2.resize(image,img_size,interpolation=2)
        image = image/255
        image = np.expand_dims(image,2)
        # print(image.shape)
        return image
    
    image = tf.py_function(aug_image_func, [image], tf.float32)
    image = tf.convert_to_tensor(image)
    return image

这里涉及的是tensorflow与python交互函数tf.py_function():

tensorflow2.x:tf.py_function()、tf.numpy_function()

tensorflow1.x:tf.py_func ()

这里会有详细解说:https://blog.csdn.net/qq_27825451/article/details/105247211

在tensorflow1.x中,可以使用sess.run()或者 x.eval来获取tensor的值:

with tf.Session() as sess:
    result = sess.run([x])  
    #result = x.eval()
    print(result)

在tensorflow2.x中,凡是可以用numpy获取值的都是指的是EagerTensorTensor没有numpy属性。所以只能使用tf.py_function()进行封装。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值