tensorflow conv2d:输入深度必须被过滤器深度整除:1 vs 256

tensorflow conv2d: input depth must be evenly divisible by filter depth: 1 vs 256

其他类似问题不适合我。我的设置简单得多,但在使用 tensorflow 时仍然出现此错误。我正在对一个代表点源的二维数组进行卷积:一个 512 x 512 数组,中间点设置为 1,一个 256x256 数组代表一个成像系统。卷积应该是系统的点扩散函数。在执行 tf.conv2d 时,我不断收到标题中的错误。我确保数组的大小与 tensorflow 一致。即,[1 512 512 1] 用于图像,[1 256 256 1] 用于内核

def convolve(arr, kernel):
    #arr: 512 x 512 2d array
    #kernel: 256 x 256 2d array

    #  make arr 4d
    f = tf.cast(tf.reshape(arr, [1, arr.shape[0], arr.shape[1], 1]), tf.float32)
        
    # make kernel 4d
    h = tf.cast(tf.reshape(kernel, [1, kernel.shape[0], kernel.shape[1], 1]), tf.float32)
        
    return tf.nn.conv2d(f, h, strides=[1, 1, 1, 1], padding="VALID")

point_source = np.zeros((512,512))
point_source[int(512/2):int(512/2)] = 1

plt.imshow(convolve(point_source, mask_array))

快到了。注意 docs 关于 filters 的状态:

A Tensor. Must have the same type as input. A 4-D tensor of shape [filter_height, filter_width, in_channels, out_channels]

这是一个工作示例:

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

def convolve(arr, kernel):
    #arr: 512 x 512 2d array
    #kernel: 256 x 256 2d array

    #  make arr 4d
    f = tf.cast(tf.reshape(arr, [1, arr.shape[0], arr.shape[1], 1]), tf.float32)
        
    # make kernel 4d
    h = tf.cast(tf.reshape(kernel, [kernel.shape[0], kernel.shape[1], 1, 1]), tf.float32)
        
    return tf.nn.conv2d(f, h, strides=[1, 1, 1, 1], padding="VALID")

point_source = np.zeros((512,512))
point_source[int(512/2):int(512/2)] = 1
mask_array = np.ones((256, 256))
plt.imshow(convolve(point_source, mask_array)[0, :, :, 0],cmap='gray')