How to Read Image in as 2-dimentional Array Python
Image processing with numpy
Martin McBride, 2021-09-21
Tags image processing rgb transparency
Categories numpy pillow
In this section, nosotros will learn how to utilise NumPy to shop and dispense image data. We volition use the Python Imaging Library (PIL) to read and write data to standard file formats.
This article explains how image data is stored in a NumPy array. Other articles include:
- NumPy image operations - cropping, padding, and flipping images using NumPy.
- NumPy epitome transformations - scaling, rotating, and general affine transforms on images using the ndimage module from the SciPy parcel.
If you lot want to larn more about numpy in full general, try the other tutorials.
Before trying these examples you will need to install the NumPy and Pillow packages (Pillow is a fork of the PIL library).
Creating RGB Images
Here is a 5 by 4 pixel RGB prototype:
The paradigm contains 4 lines of pixels. Each line of pixels contains 5 pixels. Each pixel contains 3 bytes (representing the red, greenish and blue values of the pixel color):
RGB images are normally stored as iii-dimensional arrays of viii-scrap unsigned integers. The shape of the assortment is:
Hither is how we create an assortment to represent a v pixel wide by 4 pixel high image:
import numpy as np width = 5 height = 4 array = np . zeros ([ height , width , 3 ], dtype = np . uint8 )
Notice that the beginning dimension is the elevation, and the 2d dimension is the width. That is because the data is ordered by lines, and so each line is ordered by pixels, and finally, each pixel contains 3-byte values for RGB. Each colour is represented by an unsigned byte (numpy type uint8).
Now let's fill the array with orange pixels (red=255, green=128, blue=0). We use slices to do this, the 3 values are circulate beyond all the rows and columns of the assortment:
array [:,:] = [ 255 , 128 , 0 ]
Saving an RGB image using PIL
Now we can use fromarray to create a PIL epitome from the NumPy array, and save it equally a PNG file:
from PIL import Image img = Epitome . fromarray ( array ) img . save ( 'testrgb.png' )
In the code below we will:
- Create a 200 by 100 pixel array
- Use slice notation to fill the left one-half of the assortment with orange
- Use slice notation to fill the right half of the array with bluish
Here is the complete code:
import numpy as np from PIL import Image array = np . zeros ([ 100 , 200 , 3 ], dtype = np . uint8 ) array [:,: 100 ] = [ 255 , 128 , 0 ] #Orange left side array [:, 100 :] = [ 0 , 0 , 255 ] #Blue right side img = Image . fromarray ( assortment ) img . salve ( 'testrgb.png' )
And hither is the prototype:
Creating RGBA images
An RGBA image has 4 channels (unlike an RGB prototype that has just 3). The fourth aqueduct is an alpha channel. An alpha value of 255 will make the pixel fully opaque, value 0 will brand it fully transparent, values in between will make the pixel partly transparent.
In the code beneath we create an RGBA paradigm, initially setting the same bluish and orange areas every bit before, with an blastoff value of 255. We then loop over the paradigm irresolute the alpha value of each pixel to be equal to its 10 coordinate. This ways that the pixels on the left side of the image volition be transparent, and the pixels at the right volition be almost fully opaque. The transparency varies smoothly from left to right.:
import numpy as np from PIL import Image array = np . zeros ([ 100 , 200 , 4 ], dtype = np . uint8 ) array [:,: 100 ] = [ 255 , 128 , 0 , 255 ] #Orangish left side array [:, 100 :] = [ 0 , 0 , 255 , 255 ] #Bluish right side # Set transparency depending on x position for 10 in range ( 200 ): for y in range ( 100 ): array [ y , 10 , iii ] = x img = Paradigm . fromarray ( array ) img . salve ( 'testrgba.png' )
And here is the image:
Creating greyscale images
Greyscale images are handled slightly differently. Because there is simply one channel, in that location is no need to create a 3-dimensional array, you should use a 2-dimensional array instead:
import numpy as np from PIL import Prototype array = np . zeros ([ 100 , 200 ], dtype = np . uint8 ) # Set grey value to black or white depending on x position for x in range ( 200 ): for y in range ( 100 ): if ( ten % 16 ) // 8 == ( y % 16 ) // 8 : array [ y , x ] = 0 else : assortment [ y , x ] = 255 img = Epitome . fromarray ( array ) img . save ( 'testgrey.png' )
In this instance, we have created a chequerboard image:
Reading images
Yous can read an image using the PIL open function, and convert it to an assortment using the numpy array role. Here, we read the images that were created previously, and impress their NumPy shape:
import numpy as np from PIL import Image img = Image . open ( 'testrgba.png' ) array = np . array ( img ) print ( assortment . shape ) # (100, 200, 4) img = Image . open ( 'testrgb.png' ) array = np . array ( img ) print ( array . shape ) # (100, 200, 3) img = Image . open ( 'testgrey.png' ) array = np . array ( img ) print ( array . shape ) # (100, 200)
You tin dispense the epitome data and write information technology back out to a file. For example, this code inverts a greyscale image (swapping blackness and white). and saves it dorsum:
import numpy every bit np from PIL import Image img = Epitome . open ( 'testgrey.png' ) array = np . array ( img ) array = 255 - array invimg = Image . fromarray ( array ) invimg . salve ( 'testgrey-inverted.png' )
Visit the PythonInformer Discussion Forum for numeric Python.
If you found this article useful, y'all might be interested in the book NumPy Recipes or other books past the same writer.
Prev
Popular tags
2d arrays abstract information type alignment and angle animation arc assortment arrays behavioural blueprint bezier curve built-in part callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data types design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate make full filter font font style for loop function function composition function plot functools game evolution generativepy tutorial generator geometry gif gradient greyscale higher order function hsl html image image processing imagesurface immutable object alphabetize inner part input installing iter iterable iterator itertools l arrangement lambda function len line linear slope linspace list listing comprehension logical operator lru_cache magic method mandelbrot mandelbrot ready map monad mutability named parameter numeric python numpy object open up operator optional parameter or fractional application path design permutations polygon positional parameter impress pure function python standard library radial gradient range recipes rectangle recursion reduce repeat rgb rotation roundrect scaling sector segment sequence setup shape singleton slice slicing audio spirograph sprite foursquare str stream cord stroke structural blueprint subpath symmetric encryption template text text metrics tinkerbell fractal transform translation transparency triangle tuple turtle unpacking user infinite vectorisation webserver website while loop zip
Source: https://www.pythoninformer.com/python-libraries/numpy/numpy-and-images/
0 Response to "How to Read Image in as 2-dimentional Array Python"
Post a Comment