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

Sma*_*ess 4 python opencv numpy

我正在使用它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)
Run Code Online (Sandbox Code Playgroud)

每个图像具有718x686像素/维度.有100张图片.

我不想在718x686上工作,我想将像素组合成一个维度.也就是说,形状应该如下:(100,492548,3).无论如何,无论是在OpenCV(或任何其他图书馆)或Numpy允许我这样做?

Eri*_*ric 6

无需修改您的阅读功能:

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)
Run Code Online (Sandbox Code Playgroud)


Mul*_*ter 6

万一有人想要。这是执行此操作的一般方法

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:])
Run Code Online (Sandbox Code Playgroud)

使用此功能,您可以像这样使用它:

imgs = combine_dims(imgs, 1) # combines dimension 1 and 2
# imgs.shape = (100, 718*686, 3)
Run Code Online (Sandbox Code Playgroud)