Active May 02, 2021    /    Viewed 5401    /    Comments 0    /    Edit

Examples of how import and rotate an image using matplotlib:

### Import an image with matploitlib

To import an image in python, it is possible to use matplotlib::

````from matplotlib import image`

`img = image.imread("eiffel-tower.jpeg")`
```

Note:

````print( type(img) )`
`print( img.shape )`
```

returns

````<class 'numpy.ndarray'>`
```

and

````(1280, 850, 3)`
```

### Plot the image with matploitlib

To plot the imported image, a solution is to use imshow:

````plt.imshow(img)`

`plt.show()`
```

### Rotate the image with scipy.ndimage

To rotate an image a solution is to use ndimage:

````import scipy.ndimage as ndimage`

`angle = 45 # in degrees`

`new_data = ndimage.rotate(data, angle, reshape=True)`

`plt.imshow(new_data)`

`plt.savefig("rgb_image_rotation_scipy_matplotlib_02.png", bbox_inches='tight', dpi=100)`

`plt.show()`
```

Note: "reshape=True" extend automatically the size of the image to display it entirely.

If reshape=False

````angle = 45 # in degrees`

`new_data = ndimage.rotate(data, angle, reshape=False)`

`plt.imshow(new_data)`

`plt.savefig("rgb_image_rotation_scipy_matplotlib_03.png", bbox_inches='tight', dpi=100)`

`plt.show()`
```

it returns

### Create a loop to rotate the image

````for angle in np.linspace(0,360,9):`

`    new_data = ndimage.rotate(data, angle, reshape=False)`

`    plt.imshow(new_data)`

`    plt.savefig("rgb_image_rotation_scipy_matplotlib_angle_{}.png".format(angle), bbox_inches='tight', dpi=100)`

`    plt.show()`
```

returns:

### Example of application: create an animated image (gif)

An example of application: (see also how to create an animated image (GIF) using python and Imagemagick)

````import os`

`os.system("convert -delay 100 rgb_image_rotation_scipy_matplotlib_angle_* eiffel-tower.gif")`
```

returns

### References

##### Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!

Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount