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

时间:2016-10-26 22:26:33

标签: python opencv tensorflow

我希望使用python和opencv从视频中捕获帧,然后使用tensorflow对捕获的Mat图像进行分类。问题是我不知道如何将de Mat格式转换为3D Tensor变量。这就是我现在用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})

我将不胜感激任何帮助,提前谢谢

5 个答案:

答案 0 :(得分:11)

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

为了进入初始v3,你需要使用Mult:0 Tensor作为入口点,这需要一个具有布局的4维张量:[批量索引,宽度,高度,通道] 最后三个在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)

答案 1 :(得分:4)

看起来您使用预先训练和预定义的Inception模型,该模型具有名为$(function() { $(".poslovni").click(function(e) { $(".mega-dropdown").toggle().toggleClass("intro"); e.stopPropagation(); }); $(document).click(function(e) { $('.intro').hide().removeClass('intro'); }); }); 的张量。如果是这样,这个张量需要一个包含JPEG图像字节的标量字符串。

您有几个选项,一个是在网络中寻找将JPEG转换为矩阵的节点。我不确定MAT格式是什么,但这将是DecodeJpeg/contents:0表示。如果您可以使用该格式获取图像,则可以将[height, width, colour_depth]字符串替换为要输入的节点的名称。

另一种选择是简单地将图像转换为JPEG并直接输入。

答案 2 :(得分:4)

使用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)

答案 3 :(得分:1)

您应该能够将opencv mat格式转换为numpy数组:

np_image_data = np.asarray(image_data)

一旦你将数据作为一个numpy数组,你就可以通过feeding mechanism将它传递给张量流,就像@thesonyman101所引用的链接一样:

feed_dict = {some_tf_input:np_image_data}
predictions = sess.run(some_tf_output, feed_dict=feed_dict)

答案 4 :(得分:0)

在我的情况下,我必须从文件中读取一个图像,进行一些处理然后注入到初始阶段以从称为最后一层的要素图层获得返回。 我的解决方案虽然简短但有效。

        img = cv2.imread(file)
        ... do some processing 
        img_as_string = cv2.imencode('.jpg', img)[1].tostring()
        features = sess.run(last_layer, {'DecodeJpeg/contents:0': img_as_string})