Python code to take 2 photographs and crop one photo into another

bhavya sharma
2 min readAug 14, 2023

--

In the first code ,we are using haarcascades face detection from cv2 module to automatically detect face from the photographs which have been loaded on photo1 ,crop it and paste it on photo2.

import cv2

# Load the Haarcascades face detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + ‘haarcascade_frontalface_default.xml’)

# Load the two photographs
photo1 = cv2.imread(‘image4.jpg’)
photo2 = cv2.imread(‘image3.jpg’)

# Detect faces in the first photo
faces = face_cascade.detectMultiScale(photo1, scaleFactor=1.1, minNeighbors=5)

# Loop through each detected face
for (x, y, w, h) in faces:
# Crop the face from the first photo
cropped_face = photo1[y:y+h, x:x+w]

# Resize the cropped face to match the size of the face in the second photo
cropped_face = cv2.resize(cropped_face, (w, h))

# Paste the cropped face onto the second photo
photo2[y:y+h, x:x+w] = cropped_face

# Show the final combined photo
cv2.imshow(‘Combined Photo’, photo2)
cv2.waitKey(0)
cv2.destroyAllWindows()

You can also use this second code to crop an image and paste it on another image.

from PIL import Image

# Open the two pictures
picture_1 = Image.open(“image1.jpg”)
picture_2 = Image.open(“image2.jpg”)

# Crop the face from Picture 1
face_box = (100, 100, 100, 100) # Define the area to crop (left, top, right, bottom)
cropped_face = picture_a.crop(face_box)

# Resize the cropped face to fit nicely on Picture 2
cropped_face = cropped_face.resize((100, 130))

# Paste the cropped face onto Picture 2
paste_position = (70, 10) # Where to paste the cropped face on Picture B
picture_2.paste(cropped_face, paste_position)

# Save the result to a new picture
picture_2.save(“result_picture.jpg”)

# Show the result
picture_2.show()

--

--