1. 程式人生 > >Openv和Tensorflow中的image相互轉換

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 <class 'numpy.ndarray'>,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進行轉換,效果是一樣的。