如何在numpy数组中合并维度?

2024-07-05 08:09:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用OpenCV将图像读入numpy.array,它们的形状如下。

import cv2

def readImages(path):
    imgs = []
    for file in os.listdir(path):
        if file.endswith('.png'):
            img = cv2.imread(file)
            imgs.append(img)
    imgs = numpy.array(imgs)
    return (imgs)

imgs = readImages(...)
print imgs.shape  # (100, 718, 686, 3)

每个图像都有718x686像素/维度。有100幅图像。

我不想在718x686上工作,我想把像素合并成一个一维。也就是说,形状应该像:(100,492548,3)。OpenCV(或其他任何库)或Numpy中是否允许我这样做?


Tags: path图像importnumpyimgfordef像素
3条回答

不修改阅读功能:

imgs = readImages(...)
print imgs.shape  # (100, 718, 686, 3)

# flatten axes -2 and -3, using -1 to autocalculate the size
pixel_lists = imgs.reshape(imgs.shape[:-3] + (-1, 3))
print pixel_lists.shape  # (100, 492548, 3)

以防有人想要。这里有一个一般的方法

import functools
def combine_dims(a, i=0, n=1):
  """
  Combines dimensions of numpy array `a`, 
  starting at index `i`,
  and combining `n` dimensions
  """
  s = list(a.shape)
  combined = functools.reduce(lambda x,y: x*y, s[i:i+n+1])
  return np.reshape(a, s[:i] + [combined] + s[i+n+1:])

有了这个功能,您可以这样使用它:

imgs = combine_dims(imgs, 1) # combines dimension 1 and 2
# imgs.shape = (100, 718*686, 3)
import cv2
import os
import numpy as np

def readImages(path):
    imgs = np.empty((0, 492548, 3))
    for file in os.listdir(path):
        if file.endswith('.png'):
            img = cv2.imread(file)
            img = img.reshape((1, 492548, 3))
            imgs = np.append(imgs, img, axis=0)
    return (imgs)

imgs = readImages(...)
print imgs.shape  # (100, 492548, 3)

诀窍是重塑并附加到numpy数组。对向量的长度(492548)进行硬编码是不好的做法,所以如果我是你,我还会添加一行来计算这个数字并将其放入变量中,以便在脚本的其余部分中使用。

相关问题 更多 >