如何调整 cvtColor 灰度函数,使其保持 RGB 的尺寸
How can I adjust the cvtColor grayscale function so that it keeps a dimension for RGB
函数:cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
如果我输入一张 32x32x3 的图像(R/G/B 为 3),它将输出一张 32x32 的图像。但是,我需要它 return 一个 32x32x1 的图像,这样我就可以将它用于 tensorflow。如何调整功能?
在 TensorFlow 中,您可以使用 tf.expand_dims(img, 2)
操作或 TensorFlow 索引运算符将 32x32 矩阵转换为 32x32x1 张量:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_tensor = tf.constant(img)
img_expanded = tf.expand_dims(img, 2) # or `img[:, :, tf.newaxis]`
同样可以使用 NumPy 索引实现:
import numpy as np
# ...
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_expanded = img[:, :, np.newaxis]
import numpy as np
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_expanded = img[np.newaxis,:, :, np.newaxis]
这也有效
函数:cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
如果我输入一张 32x32x3 的图像(R/G/B 为 3),它将输出一张 32x32 的图像。但是,我需要它 return 一个 32x32x1 的图像,这样我就可以将它用于 tensorflow。如何调整功能?
在 TensorFlow 中,您可以使用 tf.expand_dims(img, 2)
操作或 TensorFlow 索引运算符将 32x32 矩阵转换为 32x32x1 张量:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_tensor = tf.constant(img)
img_expanded = tf.expand_dims(img, 2) # or `img[:, :, tf.newaxis]`
同样可以使用 NumPy 索引实现:
import numpy as np
# ...
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_expanded = img[:, :, np.newaxis]
import numpy as np
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_expanded = img[np.newaxis,:, :, np.newaxis]
这也有效