在open cv2 python中使用Tensor flow 2.0对象的方法是什么,为什么这么迂回?

Sye*_*bas 5 python training-data python-3.x eager-execution tensorflow2.0

我使用张量流 api (2.0) 加载图像,如下所示:

def load(image_file):
  image = tf.io.read_file(image_file)
  image = tf.image.decode_jpeg(image)
Run Code Online (Sandbox Code Playgroud)

现在我有了这个对象,我想显示这个图像,我可以简单地使用 matplotlib.pyplot,这很有效。

plt.figure()
plt.imshow(re/255.0)
plt.show()
Run Code Online (Sandbox Code Playgroud)

然而,从一开始就用 OpenCV2 尝试这个是有问题的,大多数示例来自 1.0,基于 .eval() 会话的 numpy 转换建议。一种方法是首先将张量流对象转换为 numpy,这是 API 文档中执行此操作的函数:

TensorFlow
API r2.0
TensorFlow Core 2.0a
Python
tf.make_ndarray
Create a numpy ndarray from a tensor.
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这不起作用,我得到了许多错误,而我只想做一些简单的事情,然后使用一些开放的 cv2 函数,如重新映射、调整大小等:

文件“C:\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py”,第 426 行,调用中 self._initialize(args, kwds, add_initializers_to=initializer_map) 文件“C:\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py”,第 370 行,在 _initialize *args, **kwds 中) ) 文件“C:\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py”,第 1313 行,在 _get_concrete_function_internal_garbage_collected graph_function, _, _ = self._maybe_define_function(args, kwargs) 文件“C: \Python\Python37\lib\site-packages\tensorflow\python\eager\function.py”,第 1580 行,在 _maybe_define_function graph_function = self._create_graph_function(args, kwargs) 文件“C:\Python\Python37\lib\site-包\tensorflow\python\eager\function.py”,第 1512 行,在 _create_graph_function capture_by_value=self._capture_by_value),文件“C:\Python\Python37\lib\site-packages\tensorflow\python\framework\func_graph.py”,第 694 行,在 func_graph_from_py_func func_outputs = python_func(*func_args, **func_kwargs) 文件“C:\Python\Python37\lib\site -packages\tensorflow\python\eager\def_function.py”,第 317 行,在wrapped_fn 中返回weak_wrapped_fn()。包裹(*args, **kwds) 文件 "C:\Python\Python37\lib\site-packages\tensorflow\python\framework\func_graph.py", line 686, in wrapper ), args, kwargs) 文件 "C:\ Python\Python37\lib\site-packages\tensorflow\python\autograph\impl\api.py”,第 392 行,converted_call 结果=converted_f(*effective_args, **kwargs) 文件“C:\Users\syeda\AppData\ Local\Temp\tmpnahp3og4.py”,第 32 行,在 tf__random_deform im2 = ag__.converted_call('make_ndarray', tf, ag__.ConversionOptions(recursive=True,verbose=0, strip_decorators=(tf.function, defun_9, ag__.convert) , ag__.do_not_convert, ag__.converted_call), force_conversion=False, optional_features=(), internal_convert_user_code=True), (real_image,), {}) 文件“C:\Python\Python37\lib\site-packages\tensorflow\python \autograph\impl\api.py",第 267 行,在converted_call return _call_unconverted(f, args, kwargs) File "C:\Python\Python37\lib\site-packages\tensorflow\python\autograph\impl\api.py",第188行,在_call_unconverted return f( *args, **kwargs) 文件 "C:\Python\Python37\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 596, in MakeNdarray shape = [d.size for d in tensor.tensor_shape .dim] AttributeError: 'Tensor' 对象没有属性 'tensor_shape'在 MakeNdarray shape = [d.size for d in tensor.tensor_shape.dim] AttributeError: 'Tensor' 对象没有属性 'tensor_shape'在 MakeNdarray shape = [d.size for d in tensor.tensor_shape.dim] AttributeError: 'Tensor' 对象没有属性 'tensor_shape'

2018 年 5 月 5 日更新:在搜索更多之后,我发现这与 Tensorflow 图执行有关。我有一个功能

def load_image_train(image_file):
  input_image, real_image = load(image_file)
 print(type(real_image))
  print(real_image.shape)
  some_image = Open CV operations like filtering, jitter etc performed on real_image
return some_image
Run Code Online (Sandbox Code Playgroud)

当使用 .numpy() 属性急切地调用时,这很好用,但是当像下面的代码一样调用时,以及当您尝试检查 real_image 是什么及其类型时

类“tensorflow.python.framework.ops.Tensor”(无,无,无)

请指教。

# Input pipeline
train_dataset = tf.data.Dataset.list_files(PATH+'train/*.jpg')
train_dataset = train_dataset.shuffle(BUFFER_SIZE)
train_dataset = train_dataset.map(load_image_train,
                               num_parallel_calls=tf.data.experimental.AUTOTUNE)
train_dataset = train_dataset.batch(1)
Run Code Online (Sandbox Code Playgroud)

2018 年 5 月 5 日更新:我决定对数据进行预处理,因此我不必担心在数据加载期间使用任何 opencv 功能。但是在训练的时候我还是想做一些openCV的操作。现在根据@giser_yugang 的建议,我尝试使用 py_function,将 opencv 操作包装在 py_function 中,并在包装​​器 tf.function 中调用该函数。这个包装器 tf.function 我在训练步骤中调用。然而,我从这个包装函数得到的输出是这样的:

class 'tensorflow.python.framework.ops.Tensor'
unknown
Run Code Online (Sandbox Code Playgroud)

然后,如果我尝试在下一个列车步骤操作中使用这个张量,我会得到一个

incompatible with the layer: its rank is undefined, but the layer requires a defined rank.
Run Code Online (Sandbox Code Playgroud)

如果我在训练步骤中不使用这个 py_function 包装器并直接使用 opencv 尝试 numpy 操作,我会得到另一个错误

AttributeError: 'Tensor' object has no attribute 'numpy'
Run Code Online (Sandbox Code Playgroud)

我想这两种方式你都赢不了!

nes*_*uno 7

使用 OpenCV + Tensorflow 2.0 非常简单。

假设当前目录中有图像“wink.jpg”(请参阅​​附件中的 wink 图像),那么可以使用 Tensorflow 2.0 读取 JPEG 图像并获取tf.Tensordtype=uint8 的图像,从中获取 numpy 数组并使用 OpenCV 对其进行可视化(按照 OpenCV 的需要,采用 BGR 格式)。

import tensorflow as tf
import cv2


def load(image_file):
    image = tf.io.read_file(image_file)
    image = tf.image.decode_jpeg(image)
    return image


wink = load("wink.jpg")
print(wink.shape, wink.dtype)

# Get a Numpy BGR image from a RGB tf.Tensor
image = cv2.cvtColor(wink.numpy(), cv2.COLOR_RGB2BGR)

cv2.imshow("image", image)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)

眨眼

如果您遇到与 Graph 架构相关的问题,可能是因为您:

  • 或者使用tf.function将代码转换为图形(在这种情况下只需删除注释)
  • 或者在tf.data.Dataset方法内部使用 OpenCV(在这种情况下,不要使用 OpenCV 或tf.py_func在需要 OpenCV 的地方使用)
  • 或者使用错误版本的 Tensorflow,默认情况下不是启用 eager 模式的 2(通过运行检查一切是否正常pip list |grep tfpip list | grep tensor如果您看到一些奇怪的内容,例如安装了超过 1 个版本的 TF,我建议先删除环境新安装)。