Generate image CAPTCHA using python

In this article we shall see how to generate image CAPTCHA using python. This can be achieved with a few lines of code with a help of a python library called captcha. Let us get started with the installation of this package. This will be extremely helpful if you are using python as backend for your site where your login system uses CAPTCHAs for confirmation.


This package can be installed easily using pip as

pip install captcha

We can also clone the repo from here, change the directory to the downloaded one and then run the following command on the terminal.

python install

Make sure you are in the same directory as the file. Once we have installed this we are good to go.

Generate an image CAPTCHA

First of all we have to generate a random string consisting of both alphabets and numbers. This will be used to generate the CAPTCHA.

You can also specify the number of characters we want in our string by specifying the value inside the range function.

The output of the above code is,


Let us look at the complete code example to generate the image CAPTCHA.

This will generate an image like this.


How it works?

  1. First we import the ImageCaptcha class from the captcha library.
  2. Then we generate a random text using string and random modules.
  3. Then we initialise the ImageCaptcha class.
  4. After that we call the generate method by providing the text as input to the generate method.
  5. Finally we call the write method by providing the text and name of the output file as input to the write method.


That is it. We have generated captchas using python in just 4 lines of code. Hope this article is helpful. Bookmark us to get new articles everyday.

Happy coding!

One thought on “Generate image CAPTCHA using python

Leave a Reply

Your email address will not be published. Required fields are marked *