[英]How to retrieve with and height of an image tensor returned by tf.image.decode_jpeg?
我嘗試設置一個圖像管道,該管道為裁剪圖像的Tensorflow構建圖像數據集。 我遵循了本教程,但是我想將文件裁剪為正方形,並且在不保留寬高比的情況下不要調整其大小。 我不知道如何獲得它們的尺寸。
#
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
#
import glob
AUTOTUNE = tf.data.experimental.AUTOTUNE
IMAGE_SIZE = 192
def preprocess_image(path):
img_raw = tf.io.read_file(path)
img_tensor = tf.image.decode_jpeg(img_raw, channels=3)
print("img_tensor")
print(img_tensor)
height = img_tensor.shape[0]
print("height")
print(height)
return img_tensor
files_path = glob.glob('./images/*.jpeg')
image_count = len(files_path)
path_ds = tf.data.Dataset.from_tensor_slices(files_path)
path_ds.map(preprocess_image, num_parallel_calls=AUTOTUNE)
tf.image.decode_jpeg
返回的張量形狀為:
Tensor("DecodeJpeg:0", shape=(None, None, 3), dtype=uint8)
如何獲取jpg圖片的大小?
當我以這種方式訪問它時:
#
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
#
image = tf.io.read_file('./images/4c34476047bcbbfd10b1fd3342605659.jpeg/')
image = tf.image.decode_jpeg(image, channels=3)
print("image.shape")
print(image.shape)
它打印:
image.shape
(700, 498, 3)
由於數據集延遲加載(僅根據需要進行評估),因此您面臨此問題。
本質上,如果tf讀取了文件或者我們(作為開發人員)告訴了文件,則tf只能“知道”圖像的大小。 這似乎是顯而易見的一點,但值得牢記。
因此,考慮到tf Dataset
對象可以表示任意大的數據序列(實際上,以這種方式表示無限的數據集是完全合理的),因此從設計上講,它不會預先讀取文件。 而是每當我們的下游代碼需要新的示例或批處理時,它就會讀取它們。
恐怕要知道圖像的大小或預先針對所有可能的大小進行編碼是我們的責任。
PS可以使用第二種方法的原因是,它急切地評估了(單個)張量示例。
PPS您可能已經知道,您可以在執行時使用tf.shape()
“評估”任何張量的形狀(並在數據集預處理管道中使用此結果),但是您無法預先對其進行檢查
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.