CROP AND SWAP 2 IMAGES

Saranya. S
3 min readJun 4, 2021

PRE-REQUITIES ::

* Install cv2 module
command: pip install OpenCV-python

|| OpenCV is a cross-platform library using which we can develop real-time computer vision applications.

**It mainly focuses on image processing, video capture and analysis including features like face detection and object detection.

|| OpenCV-Python makes use of Numpy , which is a highly optimized library for numerical operations with a MATLAB-style syntax.

A. CROP THE IMAGES

1.Import cv2 and numpy.

2. Load Images.

* cv2.imread() :: loads an image from the specified file.SYNTAX: cv2.imread (path)

3. Get the dimensions

4. Load the pretrained Models.

* cv2.CascadeClassifier() : used to load the models* I used frontal face pretrained model ::
https://github.com/nazmiasri95/Face-Recognition/blob/master/haarcascade_frontalface_default.xml

5. Detecting the face.

* detectMultiScale():: detect the faces. 
* This function will return a rectangle with coordinates(x,y,w,h) around the detected face.

6. To see detection.

-> Here faces indicate the above array
x1 = faces[0][0]
y1 = faces[0][1]
x2 = x1 + faces[0][2]
y2 = y1 + faces[0][3]
For img1 , For img2 ,
x1 = 226 x1 = 254
y1 = 65 y1 = 74
x2 = 226 + 138 = 364 x2 = 254 + 107 = 361
y2 = 65 + 138 = 203 y2 = 74 + 107 = 181

7. See output of detected faces.

# Add an image in the window : display  
SYNTAX :: cv2.imshow (window_name, image)
# wait for a specific time in milliseconds
SYNTAX :: cv2.waitKey()
# Destroys the window showing image
SYNTAX :: cv2.destroyAllWindows()

OUTPUT ::

B. SWAP THE CROPPED IMAGES

BASIC RULE FOR SWAPPING:
TEMP = a
b = TEMP

FOR SWAP 1 ::

* For slicing , get the values from face1 
swap1 = img1[ y1 : y2 , x1 : x2 ]
img2[ y1 : y2 , x1 : x2 ] = swap1

OUTPUT ::

FOR SWAP 2 ::

* For slicing , get the values from face1 
swap2 = img2[ y1 : y2 , x1 : x2 ]
img1[ y1 : y2 , x1 : x2 ] = swap2

OUTPUT ::

FINAL CODE :

DONE !!!

--

--