How can I extract the image pixels from 2D numpy array?

Viewed 601

I have a matrix with a shape of (100000, 20) that consists of 20 images, each (500 *200) in size. I just need to know how can I extract those pixels so that I can have the image shape of (500, 200)? I tried matrix[:,:,19] but it seems that I just grabbed the values of the last feature, except that this is not my goal. Also when I tried to display it with cv2_imshow(matrix[:,:,19], it returns a black image.

Any help please?

2 Answers

You just need to reshape it:

import numpy as np

# after loading the images in a numpy array called imgs_array
imgs_array = imgs_array.reshape((500,200,20))

EDIT: If you want to extract a single image after the reshape step, just do single_img = imgs_array[:,:,n] where n is the n-th image in the array

here my attempt at it using reshape:



#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun  6 16:43:48 2021

@author: Pietro

https://stackoverflow.com/questions/67859613/how-can-i-extract-the-image-pixels-from-2d-numpy-array?noredirect=1#comment119943691_67859613

"""

import numpy as np

import cv2 as cv

image_mia = np.random.choice([0,255] , (100000,20))

print(image_mia.shape) # sono le dimensioni, dimensions 

print(image_mia)

print('\n',image_mia.size)



image_mia2 = np.copy(image_mia)

print(image_mia2.shape) # sono le dimensioni, dimensions 

print(image_mia2)

print('\n',image_mia2.size)

image_mia2 = image_mia2.reshape(500,200,20)

print(image_mia2.shape) # sono le dimensioni, dimensions 

print(image_mia2)

print('\n',image_mia2.size)

img = 0

image_list = []

while img<20:
    image_list.append(image_mia2[:,:,img])
    img +=1

print(image_list)

for y,i in enumerate(image_list):
    print('\nshape : ',i.shape,'    size : ', i.size)
    
    cv.imwrite(str(y)+'.png',i.astype(np.uint8))

print('\nlenght :  ',len(image_list))

without code or input image I tried to guess at my best

Related