How to Integrate OpenCV with Python TKinter

In this Python TKinter article we are going to learn How to Integrate OpenCV with Python TKinter, so OpenCV is popular and open source computer vision library that provides different image processing and computer vision algorithms. Tkinter is builtin Python GUI library used to develop desktop applications. in this article we want to talk that integrating OpenCV with Tkinter to develop image processing applications.

 

 

 

How to Integrate OpenCV with Python TKinter

TKinter is already built in with Python, we need to install OpenCV for Python.

 

 

Now let’s create our basic GUI window with Python TKinter, using this code we can create simple GUI Window in Python TKinter.

 

 

 

Run the code and you will see this result

How to Integrate OpenCV with Python TKinter
Integrate OpenCV with TKinter

 

 

 

Now let’s learn that how we can integrate Python TKinter with OpenCV, to integrate OpenCV with Tkinter, you can use cv2 module to read and process images and PIL (Python Imaging Library) module to convert the images into a Tkinter compatible format.

 

This is the code that how we can show image using TKinter and OpenCV, make sure that you already have installed PIL library.

 

Using this code we can read our image with cv2.imread() method.

 

 

In here we have convereted the image to RGB, because we are reading the image using OpenCV, and OpenCV uses BGR color system and we need to convert that to RGB.

 

 

In here we have converted the image to PIL format using Image

 

 

In here the image is converted to TKinter Compatible format

 

 

Also a label is created to display the image

 

 

Run the code this is the result

How to Integrate OpenCV with Python TKinter
How to Integrate OpenCV with Python TKinter

 

 

 

Also you can do image processing, for example in this code we are converting the image to grayscale

above code reads an image using cv2.imread, applies cv2.cvtColor function with the cv2.COLOR_BGR2GRAY argument to convert the image to grayscale, and then converts the grayscale image to PIL format. and at the end  Tkinter compatible image is created using ImageTk.PhotoImage, and Label is created to display the image.

 

 

 

If you run the code this will be the result

How to Integrate OpenCV with Python TKinter
How to Integrate OpenCV with Python TKinter

 

 

 

Learn More on Python

Leave a Comment