I'm using opencv to read my grayscale images but when I read them as grayscale:
data_dir = "/.../data/"
images = []
files = glob.glob (data_dir + "*.jpg")
for file in files:
image = cv2.imread(file, 0)
images.append(image)
my image shape is actually:
images[0].shape
(2993, 670)
how can I make it (2993, 670, 1) using cv2?
You can also use np.reshape() function from numpy. Do this:
>>> 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)
Use np.expand_dims()
from numpy, since OpenCV images are just numpy arrays:
>>> 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)
Note that the axis=2
tells which dimension to expand into; in your case, you want it to be the third axis (the axes are 0-based, so 2). As stated in the docs above, you can also do:
>>> img = img[:, :, np.newaxis]
>>> img.shape
(3, 3, 1)
or even
>>> img = img[:, :, None]
>>> img.shape
(3, 3, 1)
All are equivalent, though the first is more self-documenting.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.