Openv和Tensorflow中的image相互转换

  opencv读取image直接通过cv2.imread. 获取的图片格式为BGR(三通道图像),是已经编码过的图像。
  Tensorflow通过tf.gfile.FastGFile(filename,’rb’).read()读取的图像,是图像的原始数据,还需要经过解码,才能获取图像的数据,数据的格式为RGB(三通道图像),这一点是与Opencv不同。Tensorflow提供了对jpeg和png格式图片的解码函数,例如“decode_jpeg”对jpeg格式的图片进行解码,使用encode_jpeg编码,将图像保存到本地。
  说了这么多,opencv与Tensorflow的image是如何转换的呢?请看代码:

    # First, load the image again
    filename = "/home/scyang/Pictures/12.jpg"
    def tf_read_opencv_show():
        # read image raw data
        image_raw_data = tf.gfile.FastGFile(filename,'rb').read()
        with tf.Session() as session:
            # get image height width
            height, width = image_reader.read_image_dims(session, image_data)
            # decode image to jpeg
            image = tf.image.decode_jpeg(image_raw_data)
            # result is ,can use cv2.imshow,
            # but should cvtcolor to bgr
            print(type(session.run(image)))
    raw_image_data = cv2.imread(filename)

    image = tf.placeholder(tf.uint8, [None, None, 3])
    slice = tf.slice(image, [10, 0, 0], [100, -1, -1])
    with tf.Session() as session:
        result = session.run(slice, feed_dict={image: raw_image_data})
        print(result.shape)

    cv2.imshow('image', result)
    cv2.waitKey(0)

  在上面的代码中,Tensorflow使用的是placeholder作为输入,这可以作为神经网络训练的输入端。当然也可以使用变量进行与opencv的image进行转换,效果是一样的。
  

你可能感兴趣的:(TensorFlow,Opencv)