Python OpenCV

Author - Webner

Introduction to Python OpenCV

Python OpenCV Usage:- For main modules- run pip install OpenCV-python
Python OpenCV

cv2.imread() method

This method loads an image from the specified file and if the image cannot be read due to some error, it returns an empty matrix.
If we specify to load a color image using – cv2.imread_color, then the transparency of image is neglected, to load an image in grayscale mode use – cv2.imread_grayscale.
Syntax cv2.imread(path,flag)


Using default flag
import cv2
path = r’C:\Users\….\.png’
img = cv2.imread(path)
cv2.imshow(‘image’, img)

  • Cropping with OpenCV
    import cv2
    img = cv2.imread("pic.png")
    crop_img = img[y:y+h, x:x+w] Here x, y are coordinates and h, w is margin.
    To display the image we can use
    cv2.imshow('image', img)

    waitkey function takes time as an argument in milliseconds as a delay for the window to close.

  • To rotate an image use
    rotatedimage = cv2.warpAffine(img, rotationMatrix, (width, height))
    We can also use cv2.rotate() to rotate image clockwise, anticlockwise.

    import cv2
    img = cv2.imread('inputimage.jpg')
    img_rotate_90_clockwise = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
    cv2.imwrite('image1.jpg', img_rotate_90_clockwise)

  • Similarly, we can use cv2.flip() to flip the image vertically or horizontally.

    import cv2
    img = cv2.imread('inputimage.jpg')
    img_flip_ud = cv2.flip(img, 0)
    cv2.imwrite('image2.jpg', img_flip_ud)

    Here flipcode is zero, it will flip the image vertically.
    flipcode>0 flips image horizontally and
    flipcode<0 flips vertically and horizontally

It is widely used, few applications are:-

  1. 3D structure in movies
  2. Driverless cars, robots
  3. In medical image analysis
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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