[英]openCV imread to make grayscale image (height, width, 1)
我正在使用opencv读取灰度图像,但是当我将其读取为灰度图像时:
data_dir = "/.../data/"
images = []
files = glob.glob (data_dir + "*.jpg")
for file in files:
image = cv2.imread(file, 0)
images.append(image)
我的图像形状实际上是:
images[0].shape
(2993,670)
如何使用cv2制作(2993、670、1)?
您还可以从numpy使用np.reshape()函数。 做这个:
>>> import numpy as np
>>> image = np.zeros((2993, 670), dtype=np.uint8)
>>> resized_image = np.reshape(image,(2993,670,1))
>>> resized_image.shape
(2993, 670, 1)
使用numpy中的np.expand_dims()
,因为OpenCV映像只是numpy数组:
>>> import numpy as np
>>> img = np.zeros((3, 3), dtype=np.uint8)
>>> img.shape
(3, 3)
>>> img = np.expand_dims(img, axis=2)
>>> img.shape
(3, 3, 1)
请注意, axis=2
指示要扩展到的尺寸; 在您的情况下,您希望它是第三个轴(轴从0开始,所以2)。 如以上文档所述,您还可以执行以下操作:
>>> img = img[:, :, np.newaxis]
>>> img.shape
(3, 3, 1)
甚至
>>> img = img[:, :, None]
>>> img.shape
(3, 3, 1)
所有这些都是等效的,尽管第一个是更多自我记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.