Basic Image Operations in Python OpenCV

Yash Lahoti
3 min readJun 9, 2021

Dear Readers,

This article is on how we can perform basic image operations in Python using OpenCV.

Basic knowledge of OpenCV is recommended.

Creating an image.

Image Creation
import cv2
import numpy as np
img = np.zeros([700,700,3],dtype=np.uint8)
#Creating a new array
img.fill(0)
#black background
cv2.circle(img, (350,350) , 60 , (255,255,255) , -1) #white outside
cv2.circle(img, (350,350) , 50 , (0,0,0) , -1)
#black inside
cv2.circle(img, (350,350) , 40 , (255,255,255) , -1)
#white inside
cv2.line(img , (350,360) , (320,380) , (0,0,0),10)
#left diagonal
cv2.line(img , (350,360) , (380,380) , (0,0,0),10)
#right diagonal
cv2.line(img , (350,310) , (350,390) , (0,0,0),10)
#center line
font = cv2.FONT_HERSHEY_SIMPLEX
#font style for text
cv2.putText(img,'Peace',(170,500), font,4,255,255,255),2)
cv2.imshow('Created Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Replacing a part of an image with another part from another image.

Original Images
import cv2
pic1 = cv2.imread('myimg1.jpg')
pic2 = cv2.imread('myimg2.jpg')
#creating a copy of the image so that we can have our original image as it is with us
pic3 = cv2.imread('myimg1.jpg')
pic4 = cv2.imread('myimg2.jpg')
pic1.shape
#to know the shape of the image
pic2.shape
#to know the shape of the image
crop_pic1 = pic1[10:50, 150:200]
#storing crop part of pic 1
crop_pic2 = pic2[10:50, 150:200]
#storing crop part of pic 2
cv2.imshow('Cropped Pic 1' , crop_pic1)
cv2.imshow('Cropped Pic 2' , crop_pic2)
pic3[10:50,150:200]=crop_pic2
#adding cropped part of pic 2 in pic 1
pic4[10:50,150:200]=crop_pic1
#adding cropped part of pic 1 in pic 2
cv2.imshow('Original Pic1',pic1)
#displaying original pic 1
cv2.imshow('Original Pic2',pic2)
#displaying original pic 2
cv2.imshow('Updated Pic 1' , pic3)
#displaying updated pic 1
cv2.imshow('Updated Pic 2' , pic4)
#displaying updated pic 2
cv2.waitKey(0)
Updated Image 1
Updated Image 2

Combining/Concatinating two or more images.

Input Images
import cv2
img1 = cv2.imread('cat.jpg')
img2 = cv2.imread('dog.jpg')
#check shape of image as we want to concatenate them and it is better if they are of same size
img1.shape
img2.shape
#resize image if they are not equal in size by Interpolation i.e altering an image by adding an extra part to it
img3 = cv2.resize(img1 , (256,256) , interpolation = cv2.INTER_AREA)
img4 = cv2.resize(img2 , (256,256) , interpolation = cv2.INTER_AREA)
imgh = cv2.hconcat([img3, img4])
#horizontal concatenate
imgv = cv2.vconcat([img3, img4])
#vertical concatenate
cv2.imshow('Horizontal Combine', imgh)
cv2.imshow('Vertical Combine', imgv)
cv2.waitKey()
Combined Images

--

--