You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用OpenCV将读取的灰度图像形状改为(高,宽,1)?

Question: Convert Grayscale Image Shape from (H, W) to (H, W, 1) in OpenCV

I'm reading grayscale images using OpenCV with this code:

data_dir = "/.../data/"
images = []
files = glob.glob(data_dir + "*.jpg")
for file in files:
    image = cv2.imread(file, 0)
    images.append(image)

When I check the shape of the first image:

images[0].shape

(2993, 670)

How can I adjust this to get the shape (2993, 670, 1) using OpenCV?


Answer

Hey there, I’ve dealt with this exact scenario before—especially when working with models that expect 3D input tensors even for grayscale data. Here are a couple of reliable ways to add that extra channel dimension, including both OpenCV-specific methods and a handy numpy shortcut:

1. Use OpenCV's cv2.merge()

This function lets you combine single-channel images into a multi-channel array. Since we just need to wrap our grayscale image into a single channel, we pass it as a single-element list:

# After reading the grayscale image
image = cv2.imread(file, 0)
# Add the channel dimension
image_with_channel = cv2.merge([image])
print(image_with_channel.shape)  # Output: (2993, 670, 1)

2. Modify your reading pipeline to retain the channel

Instead of reading directly as grayscale with the 0 flag, you can read the image in BGR mode (default) and then convert it to a single-channel grayscale format. Wait, actually, cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) will still give you a 2D array, but you can combine it with cv2.merge() as above. Alternatively, you can use cv2.imread with cv2.IMREAD_GRAYSCALE (same as 0) then apply the merge step—either way works.

3. Bonus: Numpy's np.expand_dims() (super concise)

While this isn’t an OpenCV function, it’s a staple in computer vision workflows for its simplicity. Just specify that you want to add the dimension along axis 2 (the channel axis):

import numpy as np

image = cv2.imread(file, 0)
image_with_channel = np.expand_dims(image, axis=2)
print(image_with_channel.shape)  # Output: (2993, 670, 1)

To update your original loop to handle all images, here’s how it would look with either method:

data_dir = "/.../data/"
images = []
files = glob.glob(data_dir + "*.jpg")
for file in files:
    image = cv2.imread(file, 0)
    # Pick your preferred method
    processed_image = cv2.merge([image])  # or np.expand_dims(image, axis=2)
    images.append(processed_image)

All these approaches will give you the (2993, 670, 1) shape you need. I usually reach for np.expand_dims for its brevity, but cv2.merge is perfect if you want to stick strictly to OpenCV tools.

内容的提问来源于stack exchange,提问作者Hao Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:10:48