簡體   English   中英

如何將TensorFlow 2D卷積(tf.nn.conv2d)應用於單個(非批處理)2D圖像?

[英]How can I apply a TensorFlow 2D Convolution (tf.nn.conv2d) to a single (non-batch) 2D image?

我想在單個圖像示例上使用函數tf.nn.conv2d() ,但是TensorFlow文檔似乎只提到將這種轉換應用於一批圖像。

文檔提到輸入圖像必須為[batch, in_height, in_width, in_channels]形狀,內核必須為[filter_height, filter_width, in_channels, out_channels]形狀。 但是,用輸入形狀[in_height, in_width, in_channels]實現2D卷積的最直接方法是什么?

這是當前方法的示例,其中img具有形狀(高度,寬度,通道):

img = tf.random_uniform((10,10,3))  # a single image
img = tf.nn.conv2d([img], kernel)[0] # creating a batch of 1, then indexing the single example

我正在重塑輸入,如下所示:

[in_height, in_width, in_channels]->[1, in_height, in_width, in_channels]->[in_height, in_width, in_channels]

當我僅對轉換一個示例感興趣時,這感覺像是不必要且昂貴的操作。

有沒有簡單/標准的方法可以完成此操作,而無需進行整形?

AFAIK無法解決。 似乎( 在這里這里 )第一個操作創建了一個副本(如果我錯了,請糾正我)。 但是,您可以改用tf.expand_dims ,因為它的冗長性使IMO更具可讀性。

另一方面,從張量取0元素在這種情況下不應該執行復制,並且幾乎是免費的。

最重要的是 ,除了語法上的一些不便(例如[0] ),這些操作絕對不會花費很多 ,尤其是在執行卷積的情況下。

順便說一句。 其他可用的替代層(例如tf.keras層)也需要批量作為第一維。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM