在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获取值的都是指的是EagerTensor,Tensor没有numpy属性。所以只能使用tf.py_function()进行封装。