Read an image with OpenCV and display it with Tkinter

OpenCV is an Open Source Computer Vision library in Python which is widely used for Research purposes in Artificial Intelligence and Machine Learning. Computer Vision Library such as OpenCV deals with image processing. We can use OpenCV to read an image and further use it for development.

Let us suppose that we want to create an application that reads an image and displays it in the window using OpenCV.

Install OpenCV by using the following command −

pip install opencv-python

Next, follow the steps given below −

  • Install OpenCV in the environment and import the library using import cv2.

  • Import NumPy and PIL (Pillow Package) for image calculation.

  • Load the Image using imread(image_location) function.

  • Split the RGB Color of the image using the split(image) function.

  • Merge the Image colors using merge(rgb) function.

  • Convert the multidimensional matrix into an image.

  • Convert the given image using PhotoImage(image= file) function.

  • Initialize a label and display the Image.


#Import the tkinter library
from tkinter import *
import numpy as np
import cv2
from PIL import Image, ImageTk

#Create an instance of tkinter frame
win = Tk()
#Load the image
img = cv2.imread('tutorialspoint.png')

#Rearrange colors
blue,green,red = cv2.split(img)
img = cv2.merge((red,green,blue))
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im)

#Create a Label to display the image
Label(win, image= imgtk).pack()


Running the above code will load and display an image in the window.

Make sure the image 'tutorialspoint.png' is located in the same folder as the program.