The Ultimate Guide of ImageMagick in Python

Python is a widely-used programming language when it comes to image processing. Whenever we deal with image data for building a model, pre-processing the images is crucial. In pre-processing, we ensure that the image has the correct dimensions and the correct type. The availability of many different types of libraries makes python an ideal choice for image processing. In python, we have a software tool – ImageMagick Python for dealing with images. We will be talking about Imagemagick in this article.

Introduction to Imagemagick

Imagemagick in python is a software tool which is used to convert images from one format to another format. It is also capable of reading and writing images of different formats.

Imagemagick can read and write images in over 200 different formats such as JPEG, PNG, GIF, PDF, TIFF, SVG, etc. Due to its versatility, it is widely in use.

ImageMagick allows us to combine image processing operations in a script. Because of that, we can apply operations to different images.

Apart from this, we can use Imagemagick to rotate images and apply transformations, cropping images, adjust image colors, apply special effects on images and draw lines, polygons, etc., on the images.

Installing Imagemagick

To use the ImageMagick software, you can install it from imagemagick.org.’ Then, you can execute the commands from the command line.

But here, we will be using ImageMagick through python. We shall implement the ImageMagick commands using Wand. In python, Wand is a binding developed by Imagemagick. Using Wand, all the functionalities of MagickWand API can be implemented.

To install ImageMagick in python, we will be installing it in the form of an apt.

!apt install imagemagick

Then, to install Wand in python, use the below pip install command.

!pip install wand

Using Wand for ImageMagick Python

In python, we will be executing all the ImageMagick commands using Wand.

Reading dimensions of an image

First, we shall use Wand to get the dimensions of a given image. For example, we will try to find the dimensions of the following image of New York City.

a sample picture
Photo by Oliver Niblett on Unsplash

We will import the Image from wand.image. Using Image, we will read that image and print its dimensions.

from wand.image import Image

ny = Image(filename ='new york.jpg')

print(ny.height, ny.width)

The output will be:

500 750

Convert image from jpg to png

We will now use the conversion feature from ImageMagick using Wand to convert the above jpg image to png format. For that, we will import Images from the wand.

After that using Image, we will read the original jpg image. Then, we will convert it using ny.convert() and then save the file in the png format.

from wand.image import Image

ny = Image(filename ='new york.jpg')
ny_convert = ny.convert('png')
ny_convert.save(filename ='converted new york.png')

On running the above code, a new file named ‘converted new york’ gets saved with a png extension.

Imagemagick Python format conversion

If you install that file, you can see the type of the file as a png file.

png file imagemagick

Blurring an image

We can use ImageMagick to blur an image too. We have to import the Image from the wand.image. Then we shall call the blur() function using ny.blur(). We will pass the ‘sigma’ argument to the blur() function.

The sigma value is basically the standard deviation which is 0 by default. We shall pass sigma value as 4. Then, we shall save the blurred image under the name ‘new york blur’ in a jpg format.

from wand.image import Image
  
ny = Image(filename ='new york.jpg')

ny.blur(sigma = 4)

ny.save(filename ="new york blur.jpg")

After executing the above code, we can see that a new jpg image has been created.

Imagemagick Python blur image

On opening the image, we can see that it has been blurred.

Imagemagick Python blurred image

Flipping an image

We can also use ImageMagick to perform transformations on images. Here, we will be flipping an image along the horizontal axis.

This will turn the image upside down. We will first use clone() function and then use flip() to flip the image. A new image named ‘flip new york’ will be created in the jpg format.

from wand.image import Image
  
ny = Image(filename ='new york.jpg')  

flip_ny = ny.clone()
flip_ny.flip()  
flip_ny.save(filename ='flip new york.jpg')

On opening that image, we can see that the image has been flipped.

Imagemagick Python flipped image

Rotating the image

Another transformation that we can apply to the image using ImageMagick is rotation. Here, we will be using the clone() function and then use the rotate() function.

We will pass the degrees we want to rotate the image as an argument to the rotate() function. Here the image has been rotated by 45 degrees.

from wand.image import Image
  
ny = Image(filename ='new york.jpg')  

flip_ny = ny.clone()
flip_ny.rotate(45)  
flip_ny.save(filename ='rotate new york.jpg')

The new rotated image is:

Imagemagick Python rotated image

Cropping an image

ImageMagick can also be used to crop a given image. We will be using the crop() function and pass four arguments to it.

The four arguments will be the dimensions of the cropped image. We will save the new image under the name ‘new york cropped’.

from wand.image import Image

ny = Image(filename ='new york.jpg')
ny.crop(50, 190, 200, 400)
ny.save(filename = 'new york cropped.jpg')

On executing the above code, we obtain the below cropped image:

Imagemagick Python cropped image

Create edges from an image

We can also create edges from a given image. Edges are the connected pixel sets that form a boundary around the objects in an image.

We will use the function edge() to pass the radius value ‘1’ as an argument. Then we save that image as ‘edge new york’ in a jpg format.

from wand.image import Image

ny = Image(filename ='new york.jpg')
ny.edge(radius = 1)
ny.save(filename="edge new york.jpg")

The new image with the edges is:

Imagemagick Python image edges

Applying sketching effect on an image

There are several special effects which we can add to a given image. Sketch is one such special effect.

The sketch function in ImageMagick accepts three arguments – radius, sigma and angle. We shall be passing these three arguments to the function. The code for applying sketch is:

from wand.image import Image

ny = Image(filename ='new york.jpg')
ny.sketch(0.5, 0.0, 98.0)
ny.save(filename="new york sketch.jpg")

The sketch output is:

color sketch

If you want a black and white sketch, simply use transform_colorspace() function and pass ‘gray’ as an argument. The output will be a grayscale sketch.

from wand.image import Image

ny = Image(filename ='new york.jpg')
ny.transform_colorspace('gray')
ny.sketch(0.5, 0.0, 98.0)
ny.save(filename="new york grayscale sketch.jpg")
grayscale sketch

Similarly, there are other special effects which we can apply to an image such as adding noise, polaroid, swirl, tint, wave, solarize, etc.

Resizing an image

ImageMagick can be used to resize given images. As we have seen before, the size of the above image is (750, 500).

We will downsample the image by resizing it. For that, we will use the resize() function. We will resize the image to (75,50) and then print the new width and height.

from wand.image import Image

ny = Image(filename ='new york.jpg')
print(ny.width, ny.height)
ny.resize(75,50)
print(ny.width, ny.height)

The output is:

750 500
75 50

Convert PDF to image

We can also convert a given pdf into an image using ImageMagick. Here, we have converted a pdf file to an image using the convert() function. Then, we iterate for each page available in the pdf and save it as separate images.

from wand.image import Image

ny = Image(filename ='pdf new york.pdf')
ny_converted = ny.convert('jpg')
for img in ny_converted.sequence:
  page = ny(image = img)
  page.save(filename='new york pdf to image.jpg')

Adding Watermark to Image

The following code can be used to add a watermark on your image. We create two instances of images and then place one above the other on mentioned coordinates.

Code:

from wand.image import Image
from wand.compat import nested

images = (
  'image.jpg',
  'logo.jpg'
)

logo = Image(filename="logo.jpg")
image = Image(filename="image.jpg")
logo.transparentize(0.33)
image.composite_channel("all_channels",
                          logo,
                          "dissolve",
                          int(image.width - logo.width - 20),
                          int(image.height - logo.height - 20))
image.save(filename='out.png')

Output:

Watermark-on-image-imagemagick

FAQ’s on Imagemagick Python

Can we use Imagemagick to draw text on an image?

Yes, we can use Imagemagick to draw a text, a polygon or a line on an image. To draw text on image, we will have to import Drawing from wand.drawing. Before is a code snippet for drawing over the same image of new york city. We have given font size as 20 and the text which will be displayed is ‘This is New York City!’

The code is:

from wand.image import Image
from wand.drawing import Drawing
ny = Image(filename =’new york.jpg’)
draw = Drawing()
draw.font_size = 20
draw.text(100, 100, ‘This is New York City!’)
draw(ny)
ny.save(filename=”text new york.jpg”)


The output image is:

Does ImageMagick have GUI?


ImageMagick does not have a robust graphical user interface (GUI) unlike other softwares such as Adobe Photoshop.

Who is mantaining ImageMagick?


Github ImageMagick Studio LLC is the organization that designs, maintains, and enhances the ImageMagick software.


That wraps up Imagemagick Python. If you have any questions, don’t forget to tell us in the comments.

Until then, Keep Learning!

Subscribe
Notify of
guest
18 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
akash jalkote
akash jalkote
2 years ago

I wanna put a logo on an image using ImageMagick how can I do that?

Pratik Kinage
Admin
2 years ago
Reply to  akash jalkote

Yes, you can do that by using convert command. Use this command to add a logo over an image –
magick convert download.jpg logo.jpg -gravity southeast -geometry +10+10 -composite OUTPUT.jpg

This command adds logo.jpg over download.jpg at the bottom right corner at an offset of 10 pixels in both the x and y axis.

Regards,
Pratik

Abinash sen
Abinash sen
2 years ago
Reply to  Pratik Kinage

Can you please do this with codes using the same example as above, but not with commands.
Thanks in advance

Pratik Kinage
Admin
2 years ago
Reply to  Abinash sen

Yes, I’ve added a section in the above post where you can apply logo.jpg on image.jpg using the wand module.

Please let me know if you have more doubts.

Regards,
Pratik

Last edited 2 years ago by Pratik Kinage
Pavankumar Yadav
Pavankumar Yadav
2 years ago
Reply to  Pratik Kinage

I want to place logo at NorthWest (top left of the corner) by using python as you mentioned above.

Pratik Kinage
Admin
2 years ago

Yes, you can change the initial coordinates of the logo overlay on line 12. So, if you want to place the logo on the top left, then use –

image.composite_channel("all_channels", logo, "dissolve", 20, 20)

This will place the logo at the top left corner with an offset of 20 pixels. You can change it according to your need.

Regards,
Pratik

Pavankumar Yadav
Pavankumar Yadav
2 years ago
Reply to  Pratik Kinage

Thanks

Mahira
Mahira
2 years ago
Reply to  akash jalkote

Can you send me that

faizan saiyad
faizan saiyad
2 years ago

How to add one watermark in multiple images using python script?

Python Pool
Admin
2 years ago
Reply to  faizan saiyad

I’d suggest you first load all the image files’ names by using os.listdir(). Then, apply a loop over each file containing .jpg, .png, and .webp in their file extension and then apply the given script from the post.

Regards,
Pratik

Ranjeet SIngh
Ranjeet SIngh
2 years ago

I want add a watermark on the image in top left side

Pratik Kinage
Admin
2 years ago
Reply to  Ranjeet SIngh

Change the coordinates of the logo. To do this change the 12th line of code to –

image.composite_channel("all_channels", logo, "dissolve", 20, 20)

Regards,
Pratik

Patrick
Patrick
2 years ago

Hi,
How can I draw a Polygon? draw.polygon(x x x x) doesn’t work.
Is there a manual available for all commands?

Regards
Patrick

Pratik Kinage
Admin
1 year ago
Reply to  Patrick

According to official docs, you can use draw.polygon. Check the documentation to verify if you’re using correct syntax.

Constantin Marian
Constantin Marian
1 year ago

Hi, Pratik. Is it possible, using python (imagemagick – wand) to extract 42 phash float values for an image? I’m trying to replicate functionality of this script in python. Thanks in advance

Pratik Kinage
Admin
1 year ago

Why do you want a 168 digit phash? You can create different types of hash for sure.

Constantin Marian
Constantin Marian
1 year ago
Reply to  Pratik Kinage

You are right. Unfortunately, I have been using that php script for several years and I already have the hash for more than 10 million images. I want to replicate that script in python to get the hash faster

Pratik Kinage
Admin
1 year ago

Can you try using
pip install imagehash and imagehash.phash(image)?
You might have to cross-check the parameters to produce the same hash values. But this might work just fine.

Regards,
Pratik