Skip to main content
 首页 » 编程设计

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

2024年11月24日8kerrycode

我像这样使用 tensorflow api (2.0) 加载图像:

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

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

plt.figure() 
plt.imshow(re/255.0) 
plt.show() 

然而,尝试使用 OpenCV2 从一开始就存在问题,大多数示例来自 1.0,带有 .eval() 基于 session 的 numpy 转换建议。一种方法是首先将 tensorflow 对象转换为 numpy,这是 API 文档中的函数:

TensorFlow 
API r2.0 
TensorFlow Core 2.0a 
Python 
tf.make_ndarray 
Create a numpy ndarray from a tensor. 

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

File "C:\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 426, in call self._initialize(args, kwds, add_initializers_to=initializer_map) File "C:\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 370, in _initialize *args, **kwds)) File "C:\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 1313, in _get_concrete_function_internal_garbage_collected graph_function, _, _ = self._maybe_define_function(args, kwargs) File "C:\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 1580, in _maybe_define_function graph_function = self._create_graph_function(args, kwargs) File "C:\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 1512, in _create_graph_function capture_by_value=self._capture_by_value), File "C:\Python\Python37\lib\site-packages\tensorflow\python\framework\func_graph.py", line 694, in func_graph_from_py_func func_outputs = python_func(*func_args, **func_kwargs) File "C:\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 317, in wrapped_fn return weak_wrapped_fn().wrapped(*args, **kwds) File "C:\Python\Python37\lib\site-packages\tensorflow\python\framework\func_graph.py", line 686, in wrapper ), args, kwargs) File "C:\Python\Python37\lib\site-packages\tensorflow\python\autograph\impl\api.py", line 392, in converted_call result = converted_f(*effective_args, **kwargs) File "C:\Users\syeda\AppData\Local\Temp\tmpnahp3og4.py", line 32, in 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,), {}) File "C:\Python\Python37\lib\site-packages\tensorflow\python\autograph\impl\api.py", line 267, in converted_call return _call_unconverted(f, args, kwargs) File "C:\Python\Python37\lib\site-packages\tensorflow\python\autograph\impl\api.py", line 188, in _call_unconverted return f(*args, **kwargs) File "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' object has no attribute '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 

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

class 'tensorflow.python.framework.ops.Tensor' (None, None, None)

请指教。

# 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) 

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

class 'tensorflow.python.framework.ops.Tensor' 
unknown 

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

incompatible with the layer: its rank is undefined, but the layer requires a defined rank. 

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

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

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

请您参考如下方法:

使用 OpenCV + Tensorflow 2.0 非常简单。

假设我们在当前目录中有图像“wink.jpg”(见附加的 wink 图像),那么可以使用 Tensorflow 2.0 读取 JPEG 图像并获得 tf.Tensor 使用 dtype=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() 

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

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