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

19 篇文章 1 订阅
6 篇文章 0 订阅

 在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()进行封装。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是使用tensorflow.js加载tflite模型进行图片识别并打印结果的代码示例: ```javascript // 1. 加载tensorflow.js库和模型文件 import * as tf from '@tensorflow/tfjs'; import { loadGraphModel } from '@tensorflow/tfjs-converter'; const modelUrl = 'path/to/lite-model_keras-ocr_float16_2.tflite'; const model = await loadGraphModel(modelUrl, { fromTFHub: false }); // 2. 加载图片并进行预处理 const img = document.getElementById('inputImage'); // 获取图片元素 const tensor = tf.browser.fromPixels(img).toFloat(); // 转换为float类型 const resized = tf.image.resizeBilinear(tensor, [32, 256]); // 调整大小为32x256 const expanded = resized.expandDims(); // 增加一个维度以适应模型输入格式 // 3. 使用模型进行预测 const output = model.predict(expanded); const prediction = output.dataSync(); // 获取模型输出结果 // 4. 解析预测结果并打印文字识别结果 const labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; // 标签列表 const threshold = 0.5; // 阈值 let result = ''; for (let i = 0; i < prediction.length; i++) { if (prediction[i] > threshold) { result += labels[i]; } } console.log('识别结果:', result); // 打印文字识别结果 ``` 需要注意的是,由于使用了tensorflow.js加载tflite模型,因此需要在服务端使用Node.js环境或者使用类似Webpack等工具进行打包后才能运行。同时,上述代码中的`path/to/lite-model_keras-ocr_float16_2.tflite`需要替换为实际模型文件的路径。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值