Loading Image in Python using OpenCV

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.


First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3


In this tutorial, I will show you how to load an image in python and display it in a window using OpenCV library.


Python: cv2.imread(filename[, flags]) → retval

Loads an image from a file.


  • filename– Name of file to be loaded.
  • flags – Flags specifying the color type of a loaded image:
    1. cv2.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the default flag.
    2. cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode
    3. cv2.IMREAD_UNCHANGED : Loads image as such including alpha channel

Note: Instead of these three flags, you can simply pass integers 1, 0 or -1 respectively

Python: cv2.imshow(winname, mat) → None

Displays an image in the specified window.


  • winname – Name of the window.
  • image – Image to be shown.

The function imshow displays an image in the specified window. If the window was created with the CV_WINDOW_AUTOSIZE flag, the image is shown with its original size. Otherwise, the image is scaled to fit the window.


  • Load Image using cv2.imread()
  • Create window using cv2.namedWindow()
  • Display Image using cv2.imshow()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2
import numpy as np
import sys

def main():
    imgpath = "Hanif.jpg"

    img = cv2.imread(imgpath,cv2.IMREAD_COLOR) # load image from file
    cv2.namedWindow('Hanif',cv2.WINDOW_AUTOSIZE) # for resizing use 'cv2.WINDOW_NORMAL'

    cv2.imshow('Hanif', img) # display the image
    cv2.waitKey(0) # wait for keyboard interrupt
    cv2.destroyAllWindows() # destroy all the windows

if __name__ == "__main__":


Load-Image Loading Image in Python using OpenCV

life2coding_icon [] Loading Image in Python using OpenCV

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.