将python opencv mat图像转换为tensorflow图像数据

新手上路,请多包涵

我想用 python 和 opencv 从视频中捕获帧,然后用 tensorflow 对捕获的 Mat 图像进行分类。问题是我不知道如何将 de Mat 格式转换为 3D 张量变量。这就是我现在使用 tensorflow 的方式(从文件加载图像):

 image_data = tf.gfile.FastGFile(imagePath, 'rb').read()
with tf.Session() as sess:
    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
    predictions = sess.run(softmax_tensor,
                           {'DecodeJpeg/contents:0': image_data})

我将不胜感激任何帮助,在此先感谢

原文由 Txeif 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 816
2 个回答

使用 imread 加载 OpenCV 图像,然后将其转换为 numpy 数组。

为了输入 inception v3,您需要使用 Mult:0 Tensor 作为入口点,这需要一个具有布局的 4 维 Tensor:[Batch index,Width,Height,Channel] 最后三个来自 cv 非常好: :Mat,第一个只需要是 0,因为你不想提供一批图像,而是单个图像。代码如下:

 #Loading the file
img2 = cv2.imread(file)
#Format for the Mul:0 Tensor
img2= cv2.resize(img2,dsize=(299,299), interpolation = cv2.INTER_CUBIC)
#Numpy array
np_image_data = np.asarray(img2)
#maybe insert float convertion here - see edit remark!
np_final = np.expand_dims(np_image_data,axis=0)

#now feeding it into the session:
#[... initialization of session and loading of graph etc]
predictions = sess.run(softmax_tensor,
                           {'Mul:0': np_final})
#fin!

亲切的问候,

克里斯

编辑:我刚刚注意到,初始网络希望将强度值标准化为 [-0.5,0.5] 的浮点数,因此请在构建 RGB 图像之前使用此代码转换它们:

 np_image_data=cv2.normalize(np_image_data.astype('float'), None, -0.5, .5, cv2.NORM_MINMAX)

原文由 Chris VdoP 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 Tensorflow 2.0 和 OpenCV 4.2.0,您可以通过这种方式转换:

 import numpy as np
import tensorflow as tf
import cv2 as cv

width = 32
height = 32

#Load image by OpenCV
img = cv.imread('img.jpg')

#Resize to respect the input_shape
inp = cv.resize(img, (width , height ))

#Convert img to RGB
rgb = cv.cvtColor(inp, cv.COLOR_BGR2RGB)

#Is optional but i recommend (float convertion and convert img to tensor image)
rgb_tensor = tf.convert_to_tensor(rgb, dtype=tf.float32)

#Add dims to rgb_tensor
rgb_tensor = tf.expand_dims(rgb_tensor , 0)

#Now you can use rgb_tensor to predict label for exemple :

#Load pretrain model, made from: https://www.tensorflow.org/tutorials/images/cnn
model = tf.keras.models.load_model('cifar10_model.h5')

#Create probability model
probability_model = tf.keras.Sequential([model,
                                     tf.keras.layers.Softmax()])
#Predict label
predictions = probability_model.predict(rgb_tensor, steps=1)

原文由 Bensuperpc 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题