Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine dimensions in numpy array?

I'm using OpenCV to read images into numpy.array, and they have the following shape.

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)

Each of the image has 718x686 pixels/dimension. There are 100 images.

I don't want to work on 718x686, I'd like to combine the pixels into a single dimension. That is, the shape should look like: (100,492548,3). Is there anyway either in OpenCV (or any other library) or Numpy that allows me to do that?

like image 688
SmallChess Avatar asked Apr 02 '16 08:04

SmallChess


People also ask

How do I merge two columns in NumPy?

concatenate() with axis=1. You can also concatenate two NumPy arrays column-wise by specifying axis=1. Now the resulting array is a wide matrix with more columns than rows. With axis=1 , it returns an array of arrays (Nested array).

Can we concatenate the arrays with different dimensions?

Join a sequence of arrays along an existing axis. The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). The axis along which the arrays will be joined.

Can NumPy array have mixed data types?

Introduction to Data Types In lists, the types of elements can be mixed. One index of a list can contain an integer, another can contain a string. This is not the case for arrays. In an array, each element must be of the same type.


1 Answers

Without modifying your reading function:

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)
like image 185
Eric Avatar answered Oct 11 '22 22:10

Eric