Fun with OpenCV Python

Urvishtalaviya
3 min readAug 3, 2021

Hey there!!! In this article, we going to do some fun activities with OpenCV. I assume that everybody has some little idea about computer vision and what OpenCV is meant. Let me first discuss the agenda:

👉 Create an image using the array.

👉 Take two images, crop some part of both images, and swap

👉 Take two images and combine them into one single image

Without wasting much time, let’s dive into the tasks

Create an image using the array

#importing cv2
import cv2
import numpy as np
#function for creating diamond shape with numpy array
def diamond(n):
a = np.arange(n)
b = np.minimum(a,a[::-1])
return (((b[:,None]+b)>=(n-1)//2)*1)*255
#Converting array into numpy array
img = np.array(diamond(501), np.uint8)
#Showing the image
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

While doing this task I was thinking about what to draw, I had ideas like write my name with the array, or randomly draw something. After giving a lot of thought I decided to go with the diamond pattern😂.

In this code, diamond() returns a 2D list containing 1s and 0s. For watching it as an image we must convert it into the numpy array. After converting, just use imshow() of the cv2 module. I got the results like this:

Take two images, crop some part of both images, and swap

#importing cv2 module
import cv2
import copy
import numpy as np
naruto = cv2.imread("naruto.jpg")
sasuke = cv2.imread("sasuke.jpg")
naruto_face = naruto[0:340, 128:388]
sasuke_face = sasuke[0:340, 200:460]
temp_face = copy.copy(naruto_face)
naruto[0:340, 128:388] = sasuke_face
cv2.imwrite("sasuke_new.jpg", naruto)
sasuke[0:340, 200:460] = temp_face
cv2.imwrite("naruto_new.jpg", sasuke)

For this task, I took two images of my favourite anime Naruto. The images are of Naruto Uzumaki and Sasuke Uchiha.

First I took the faces from images by converting them into arrays means I take the array index of the face and stored them into variables for swapping. And then it was easy, I just place face at the same indexes. Here is the result:

Take two images and combine them into one single image

#importing cv2 module
import cv2
import numpy as np
naruto = cv2.imread("naruto.jpg")
sasuke = cv2.imread("sasuke.jpg")
img = np.hstack([naruto ,sasuke])cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

It was the easiest task. Again I took the image of Naruto Uzumaki and Sasuke Uchiha, used hstack() of numpy module for creating a new array, and done. Here is the complete image:

It was great fun doing this task😍. Thank you all for reading this blog.

--

--

Urvishtalaviya

Competitive Programmer | Machine Learning Enthusiastic | Bigdata Enthusiastic