How to convert array to image in python

How do I convert byte array to bitmap image in Python?

Solution 2: Updated script thats convert plain image to cipher image and back to plain image. I tried: and got a next image: Solution 1: I don’t know a thing about PIL and I haven’t used Python for some time, but here is my take at this bits to bytes conversion problem.

How do I convert byte array to bitmap image in Python?

I looked a bit more into how to retrieve/update the image data more elegantly with the tools included in PIL/Pillow, and made this simple working example:

from PIL import BmpImagePlugin import hashlib from itertools import cycle keys = hashlib.md5(b"aaaabbbb").digest() input_image = BmpImagePlugin.BmpImageFile("img/tea.bmp") # extract pure image data as bytes image_data = input_image.tobytes() # encrypt image_data = bytes(a^b for a, b in zip(image_data, cycle(keys))) # create new image, update with encrypted data and save output_image = input_image.copy() output_image.frombytes(image_data) output_image.save("img/tea-encrypted.bmp") 

This way, you don’t have to worry about the BMP header size.

(links: original and encrypted image)

Updated script thats convert plain image to cipher image and back to plain image.

import os, io, hashlib, math, binascii from PIL import Image from array import array from itertools import cycle user_key = "aaaabbbb" test_image = "lena512.bmp" def generate_keys(key): round_keys = hashlib.md5(key).digest() return bytearray(round_keys) def readimage(path): with open(path, "rb") as f: return bytearray(f.read()) def generate_output_image(input_image): output_image = Image.open(io.BytesIO(input_image)) output_image.save(test_image) def xor(x,y): return x[:54] + bytearray([a^b for a, b in zip(x[54:], cycle(y))]) round_keys = generate_keys(user_key) input_image = readimage(test_image) encrypted_image = xor(input_image, round_keys) generate_output_image(encrypted_image) input_image = readimage(test_image); decrypted_image = xor(input_image, round_keys) generate_output_image(decrypted_image) 

Thanks myrmica for your help

How do I convert byte array to bitmap image in Python?, Updated script thats convert plain image to cipher image and back to plain image. import os, io, hashlib, math, binascii from PIL import Image from array import array from itertools import cycle user_key = «aaaabbbb» test_image = «lena512.bmp» def generate_keys (key): round_keys = hashlib.md5 …

How to convert an array of numbers to bitmap image in python?

PIL.Image has a function that takes a numpy array and converts it to an image: Image.from_array . You can use it to generate B&W, grayscale, RGB or RGBA images easily.

In you case, the cleanest way to build the image is:

import numpy as np from PIL import Image def get_img(width=255, height=255): data = np.arange(width * height, dtype=np.int64).reshape((height, width)) img_data = np.empty((height, width, 3), dtype=np.uint8) img_data[:, :, 0] = data // height img_data[:, :, 1] = data % width img_data[:, :, 2] = 100 return Image.fromarray(img_data) display(get_img()) 

Result image

Note that although this way of building the data needs to go through the array 3 times, it is still faster than plain-python loops. For the default values of 255 by 255 images, it is almost 30 times faster.

from PIL import Image from IPython.display import display img = Image.new('RGB', (255,255), "black") # Create a new black image list_of_pixels = list(img.getdata()) print(list_of_pixels) im2 = Image.new(img.mode, img.size) im2.putdata(list_of_pixels) display(im2) 

How to convert an array of numbers to bitmap image in, 2 Answers. PIL.Image has a function that takes a numpy array and converts it to an image: Image.from_array. You can use it to generate B&W, grayscale, RGB or RGBA images easily. import numpy as np from PIL import Image def get_img (width=255, height=255): data = np.arange (width * height, …

Читайте также:  Can php receive email

How to convert byte array to picture

Each MIME type has a signature(magic number). By first bytes its a JPEG img.

# your array arr = [255, 216, 255, 224, 0, . ] >>> bytearray(arr[:4]) bytearray(b'\xff\xd8\xff\xe0') 

FF D8 FF E0 — its a jpeg signature image.

f = open('/tmp/myimage.jpeg', 'wb') f.write(bytearray(arr)) f.close() 

and got a next image:

Python — How to convert byte array to picture, How do I convert my byte array to a picture? I want it to be in saved JPG or BMP format, not just displayed as text or on the console. This is sample array: [255, 216, 255, 224, 0, 16, 74, 70, 73

In Python, how to convert array of bits to array of bytes?

I don’t know a thing about PIL and I haven’t used Python for some time, but here is my take at this bits to bytes conversion problem.

import itertools # assuming that `bits` is your array of bits (0 or 1) # ordered from LSB to MSB in consecutive bytes they represent # e.g. bits = [0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1] will give you bytes = [128,255] bytes = [sum([byte[b]  

This code should be mostly self-explanatory.

PIL's ImagingCore can easily be converted to bytes:

from PIL import Image img = Image.open("python.jpg", "r") data = img.convert("1").getdata() bytes = bytearray(data) 

This gives you a bytearray() list of bytes which can then be manipulated or written to a file. You could write this to a file by doing:

with open("filename", "w") as f: f.write(b"".join(map(bytes, data))) 

It's probably worth noting too that Python in fact does not have a data type for bits . And that list(data) returns a list of int (s) and not "bits" as you thought ?

>>> list(data)[:10] [255, 255, 255, 255, 255, 255, 255, 255, 255, 255] >>> set(list(data)) set([0, 255]) >>> set(map(type, list(data))) set([]) 

So in reality you are not saving any data by doing this.

See: http://docs.python.org/2/library/stdtypes.html for Python data types and operations. You can perform "bit" operations, but there is no "bit" data type.

Type conversion - Python byte array to bit array, The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use …

Источник

How to convert array to image in python

Projects and Applications with NumPy

Introduction

Creating NumPy Array

  • Numpy | Array Creation
  • numpy.arange() in Python
  • numpy.zeros() in Python
  • Create a Numpy array filled with all ones
  • numpy.linspace() in Python
  • numpy.eye() in Python
  • Creating a one-dimensional NumPy array
  • How to create an empty and a full NumPy array?
  • Create a Numpy array filled with all zeros | Python
  • How to generate 2-D Gaussian array using NumPy?
  • How to create a vector in Python using NumPy
  • Python | Numpy fromrecords() method

NumPy Array Manipulation

  • Copy and View in NumPy Array
  • How to Copy NumPy array into another array?
  • Appending values at the end of an NumPy array
  • How to swap columns of a given NumPy array?
  • Insert a new axis within a NumPy array
  • numpy.hstack() in Python
  • numpy.vstack() in python
  • Joining NumPy Array
  • Combining a one and a two-dimensional NumPy Array
  • Python | Numpy np.ma.concatenate() method
  • Python | Numpy dstack() method
  • Splitting Arrays in NumPy
  • How to compare two NumPy arrays?
  • Find the union of two NumPy arrays
  • Find unique rows in a NumPy array
  • Python | Numpy np.unique() method
  • numpy.trim_zeros() in Python

Matrix in NumPy

  • Matrix manipulation in Python
  • numpy matrix operations | empty() function
  • numpy matrix operations | zeros() function
  • numpy matrix operations | ones() function
  • numpy matrix operations | eye() function
  • numpy matrix operations | identity() function
  • Adding and Subtracting Matrices in Python
  • Matrix Multiplication in NumPy
  • Numpy ndarray.dot() function | Python
  • NumPy | Vector Multiplication
  • How to calculate dot product of two vectors in Python?
  • Multiplication of two Matrices in Single line using Numpy in Python
  • Python | Numpy np.eigvals() method
  • How to Calculate the determinant of a matrix using NumPy?
  • Python | Numpy matrix.transpose()
  • Python | Numpy matrix.var()
  • Compute the inverse of a matrix using NumPy

Operations on NumPy Array

Reshaping NumPy Array

  • Reshape NumPy Array
  • Python | Numpy matrix.resize()
  • Python | Numpy matrix.reshape()
  • NumPy Array Shape
  • Change the dimension of a NumPy array
  • numpy.ndarray.resize() function – Python
  • Flatten a Matrix in Python using NumPy
  • numpy.moveaxis() function | Python
  • numpy.swapaxes() function | Python
  • Python | Numpy matrix.swapaxes()
  • numpy.vsplit() function | Python
  • numpy.hsplit() function | Python
  • Numpy MaskedArray.reshape() function | Python
  • Python | Numpy matrix.squeeze()

Indexing NumPy Array

Arithmetic operations on NumPyArray

Linear Algebra in NumPy Array

NumPy and Random Data

  • Random sampling in numpy | ranf() function
  • Random sampling in numpy | random() function
  • Random sampling in numpy | random_sample() function
  • Random sampling in numpy | sample() function
  • Random sampling in numpy | random_integers() function
  • Random sampling in numpy | randint() function
  • numpy.random.choice() in Python
  • How to choose elements from the list with different probability using NumPy?
  • How to get weighted random choice in Python?
  • numpy.random.shuffle() in python
  • numpy.random.geometric() in Python
  • numpy.random.permutation() in Python

Sorting and Searching in NumPy Array

Universal Functions

Источник

Convert a Numpy Array to Image in Python

In this tutorial, you will learn how to Convert a Numpy Array to Image in Python. Here, we are going to use the Python Imaging Library ( PIL ) Module and Numerical Python (Numpy) Module to convert a Numpy Array to Image in Python. PIL and Numpy consist of various Classes. We require only Image Class. Hence, our first script will be as follows:

from PIL import Image import numpy as np

Here, we have imported Image Class from PIL Module and Numpy Module as np. Now, let’s have a look at the creation of an array.

w,h=512,512 # Declared the Width and Height of an Image t=(h,w,3) # To store pixels # Creation of Array A=np.zeros(t,dtype=np.uint8) # Creates all Zeros Datatype Unsigned Integer

Let’s have a clearer Explanation here,

Tuple t indicates the matrix order “h x w x 3” where w,h is the height and width of an Image, 3 indicates the three colors per pixel [R, G, B].

Structure of Array:

So, lets have a look at the structure of the specified array for converting it to Image. It is as follows

A= [ [R00, G00, B00], [R01, G01, B01], [R02, G02, B02], …, [R0(h-1), G0(h-1), B0(h-1)] [R10, G10, B10], [R11, G11, B11], [R12, G12, B12], …, [R1(h-1), G1(h-1), B1(h-1)]

I think it might be complex to understand. But, it consists of [R,G,B] of each pixel of an Image. Now, lets have a look at assigning colors to the Image.

for i in range(h): for j in range(w): A[i,j]=[i%256,j%256,(i+j)%256] # Assigning Colors to Each Pixel

So, Our new Pixel will be [i,j,i+j] where, i iterates through the Height and j iterates through the Width of an Image. i.e. Red -> i%256, Green -> j%256 and Blue -> (i+j)%256.

Each Color of Pixel is Modular Divided(%) by 256 since the RGB Color Model holds the highest Color Range from 0 t0 255 Hexadecimal Values. Now, let’s have a look at converting Array into Image using Image Class.

As you have seen, Image Class Consists fromarray() Method which converts the given array to the specified Color Model(i.e. RGB Model).

Here, i is the Image Object created for the given Numpy Array. Let’s have a glance over Viewing or Showing the Image. It can be done by the show() method of Image Object. Consider the following Example

Example:

from PIL import Image import numpy as np w,h=512,512 t=(h,w,3) A=np.zeros(t,dtype=np.uint8) for i in range(h): for j in range(w): A[i,j]=[i%256,j%256,(i+j)%256] i=Image.fromarray(A,"RGB") i.show()

The output of the above code will be as follows

colorful pattern

So, In this way, we can convert a Numpy Array into Image using PIL and Numpy.

One response to “Convert a Numpy Array to Image in Python”

When run in Jupyter Notebook this code, as written above, generates the following error: TypeError Traceback (most recent call last)
in
4 t=(h,w,3)
5 A=np.zeros(t,dtype=np.uint8)
—-> 6 for i in range(h):
7 for j in range(w):
8 A[i,j]=[i%256,j%256,(i+j)%256] TypeError: ‘numpy.ndarray’ object is not callable

Источник

Оцените статью