Gant Laborde
Gant Laborde

Reputation: 6774

Convert Numpy image array to 1px high version

CONTEXT:

Google has an spritesheet of MNIST data. They took a (28, 28, 1) image and turned it into a (1, 784, 1) row of data (784 is 28*28). They then did this for all 65k images. So it fits into a nice spritesheet like so: https://storage.googleapis.com/learnjs-data/model-builder/mnist_images.png

I'm looking to make my own spritesheet of data.

I'm using numpy/PIL, so when I get an image converted to numpy, with 3 channels.

Question: How do I just flatten it out and then concatenate that flat image so it turns into an image that is width=784, height=number of images, all in RGB.

pseudocode here:

# Load image image
image_data = image.load_img("/path/to.png", target_size=(28, 28))

# Create shape (28, 28, 3)
np_train = np.array(image_data)

# Goal change (28, 28, 3) into (1, 784, 3)
# then add that to some final_image, building to final_image (num_images, 784, 3)

# then 
img = Image.fromarray(final_image)
img=.show # spritesheet of image data for consumption

EDIT: The result: https://github.com/GantMan/rps_tfjs_demo/blob/master/spritemaker/makerps.py

Upvotes: 1

Views: 684

Answers (2)

Vasilis G.
Vasilis G.

Reputation: 7859

You don't quite need numpy to do that, although I don't know if its necessary to use it, but there is a way of doing it with simple Python:

from PIL import Image

src_image = Image.open('test_image.png') # Image of size (28,28)

pixels = list(src_image.getdata()) # Get all pixel in 1D array.

dst_image = Image.new('RGB', (1,src_image.size[0] * src_image.size[1])) # Create new image with new size.

dst_image.putdata(pixels) # Place pixels in the new image.

dst_image.save('result.png') # Save the new image.

Example:

Source image:

enter image description here

Destination image:

enter image description here

Upvotes: 1

Marat
Marat

Reputation: 15738

If you question is how to concatenate multiple images into one, where each row represents a single image from the original dataset, then reshape + concatenate should do the trick:

# all_images is a list / iterator of 28x28x3 numpy arrays 
final_image = np.concatenate([img.reshape(1, -1, 3) for img in all_images])

Upvotes: 1

Related Questions