Image collage creation and Crop image swaption using numpy ,Open cv
2 min readJul 31, 2023
Greetings and best wishes for an insightful read😇 ,
Hope this blog finds you great and healthy !!😊
Lets begin with brief introduction about me…..
Hi, This is Ankit Shukla and I am working as Automation Engineer in Regulatory Reporting Domain. In this article we will discuss about below tasks:
- Take 2 images and combine it to form a single image
- Take 2 images and crop some part and swap them
1. Solution:
import cv2
import numpy as np
# Step 1: Read the two images using OpenCV
image1 = cv2.imread('img1.jpeg')
image2 = cv2.imread('img2.jpeg')
# Step 2: Resize the images to have the same dimensions (if needed)
# Assuming both images have the same dimensions, skip resizing
# Step 3: Create a new blank canvas (numpy array) with dimensions large enough to accommodate both images
canvas_width = image1.shape[1] + image2.shape[1]
canvas_height = max(image1.shape[0], image2.shape[0])
canvas = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)
# Step 4: Paste the first image onto the canvas
canvas[:image1.shape[0], :image1.shape[1]] = image1
# Step 5: Paste the second image onto the canvas, overlapping the first image
canvas[:image2.shape[0], image1.shape[1]:] = image2
# Save the combined image
cv2.imwrite('combined_image.jpg', canvas)
# Display the combined image
cv2.imshow('Combined Image', canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
2. Solution:
import cv2
# Step 1: Read the two images using OpenCV
image1 = cv2.imread('image1.jpg')
image2 = cv2.imread('image2.jpg')
# Step 2: Define the coordinates or area to crop from each image
# (y_start, y_end, x_start, x_end)
crop_region1 = (100, 400, 150, 450)
crop_region2 = (200, 500, 300, 600)
# Step 3: Crop the specified regions from the two images
crop1 = image1[crop_region1[0]:crop_region1[1], crop_region1[2]:crop_region1[3]]
crop2 = image2[crop_region2[0]:crop_region2[1], crop_region2[2]:crop_region2[3]]
# Step 4: Swap the cropped regions between the images
image1[crop_region1[0]:crop_region1[1], crop_region1[2]:crop_region1[3]] = crop2
image2[crop_region2[0]:crop_region2[1], crop_region2[2]:crop_region2[3]] = crop1
# Step 5: Combine the swapped regions and the rest of the images
swapped_image1 = image1
swapped_image2 = image2
# Display the swapped images
cv2.imshow('After Swap Image 1', swapped_image1)
cv2.imshow('After Swap Image 2', swapped_image2)
cv2.waitKey(0)
cv2.destroyAllWindows()
Thanks for reading the blog…….😊