Uses of OpenCV in Python

KAVIN KRISHNA PRASAD
2 min readAug 12, 2021

🔅 Task 4.1
📌 Create image by yourself Using Python Code

import cv2
import numpy
#it gives black image with 500*500 as dimensions
photo=numpy.zeros((500,500))
cv2.imshow(‘task1’,photo)
cv2.waitKey()
cv2.destroyAllWindows()
# inserting the shape of rectangle into the image with function rectangle(imagename,(x1,y1),(x2,y2),[B,G,R],thickness)
photo=cv2.rectangle(photo,(200,200),(300,300),[20,56,135],10)
# inserting the shape of line into the image with function line(imagename,(x1-cordinate,y1-cordinate),[B,G,R],thickness)
lphoto = cv2.line(photo,(200,210),(160,240),[120,0,135],5)
lphoto = cv2.line(photo,(300,210),(340,240),[120,0,135],5)
lphoto = cv2.line(photo,(220,300),(220,340),[120,0,135],5)
lphoto = cv2.line(photo,(280,300),(280,340),[120,0,135],5)
# inserting the shape of circle into the image with function
#circle(imagename,(centre-x1-cordinate,y1-cordinate),radius,
[B,G,R],thickness)
circle=cv2.circle(lphoto ,(250,150),45,[0,250,211],4)
circle=cv2.circle(lphoto ,(230,135),5,[0,250,211],4)
circle=cv2.circle(lphoto ,(270,135),5,[0,250,211],4)
photo=cv2.line(photo,(240,165),(260,165),[0,0,135],5)
cv2.imshow(‘photo’,photo)
cv2.waitKey()
cv2.destroyAllWindows()

🔅 Task 4.2
📌 Take 2 image crop some part of both image and swap it.

Here we are using cv2 library and crop and swap part of images.

import cv2
import numpy
#read first image
cap1 = cv2.imread(“1.jfif”)
cap1.shape
(722, 690, 3)
#display first image
cv2.imshow(“Task4.2”,cap1)
cv2.waitKey()
cv2.destroyAllWindows()
#crop first image
crop1 = cap1[75:225,275:400]
#read second image
cap2 = cv2.imread(“2.jfif”)
#display second image
cv2.imshow(“Task4.2.1”,cap2)
cv2.waitKey()
cv2.destroyAllWindows()
#crop second image
crop2 = cap2[50:200,175:300]
#replace cropped images
cap1[75:225,275:400] = cap2[50:200,175:300]
#display swapped image
cv2.imshow(“Task4.2.1”,cap1)
cv2.waitKey()
cv2.destroyAllWindows()

Output:

🔅 Task 4.3
📌 Take 2 image and combine it to form single image. For example collage

import cv2
import glob
cap1 = cv2.imread(“1.jpeg”)
cap2 = cv2.imread(“C:/Users/Saketh/Desktop/F1/tiger.png”)
#horizantal concat
college1 = cv2.hconcat([cap1,cap1])
photo = cv2.imshow(“Task4”,college1)
cv2.waitKey()
cv2.destroyAllWindows()
#vertical concat
college2 = cv2.vconcat([cap2,cap2])
photo = cv2.imshow(“Task4”,college2)
cv2.waitKey()
cv2.destroyAllWindows()
#flip and concate
cap3 = cv2.flip(cap2,1)
college3 = cv2.hconcat([cap2,cap3])
photo = cv2.imshow(“Task4”,college3)
cv2.waitKey()
cv2.destroyAllWindows()

Thanks!

--

--