Morphing One Image into Another Using python
- User
Morphing One Image into Another Using python
- Assistant
Morphing One Image into Another Using python
Morphing one image into another involves a smooth transition where the first image gradually transforms into the second image. This process is widely used in animations and visual effects to create a seamless blend between images. In Python, you can achieve image morphing using libraries like OpenCV, NumPy, and SciPy.
Below is a step-by-step guide to morphing two images using Python, including code snippets to help illustrate the process.
Python Environment: Ensure you have Python installed (preferably version 3.6 or higher).
Install Required Libraries: Install the necessary Python libraries using pip.
pip install opencv-python numpy scipy matplotlib imageio
Morphing involves two primary steps:
To achieve realistic morphing, corresponding feature points (landmarks) need to be defined on both images. These points guide the warping process to ensure that features (like eyes, nose, mouth in faces) align during the transition.
First, load the two images you want to morph. Ensure both images are the same size; if not, resize them.
import cv2
# Load images
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
# Resize images to be the same size
height, width = img1.shape[:2]
img2 = cv2.resize(img2, (width, height))
Define corresponding points (landmarks) on both images. These can be manually selected or detected automatically using facial landmark detectors like dlib (if you're working with faces).
import numpy as np
# Example points, replace with actual coordinates
points_img1 = np.array([
[x1, y1],
[x2, y2],
# ... more points
], np.float32)
points_img2 = np.array([
[x1_prime, y1_prime],
[x2_prime, y2_prime],
# ... more points
], np.float32)
Tip: For non-face images, you might need to use a tool like OpenCV's selectROI or a custom GUI to select points.
import dlib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
def get_landmarks(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rects = detector(gray)
for rect in rects:
landmarks = predictor(gray, rect)
coords = np.zeros((68, 2), dtype=np.float32)
for i in range(68):
coords[i] = (landmarks.part(i).x, landmarks.part(i).y)
return coords
return None
points_img1 = get_landmarks(img1)
points_img2 = get_landmarks(img2)
Note: Download shape_predictor_68_face_landmarks.dat from here and extract it.
Include the corners and edges of the image as additional points to ensure the entire image morphs smoothly.
def add_boundary_points(points, w, h):
boundary_pts = np.array([
[0, 0], [w//2, 0], [w-1, 0],
[w-1, h//2], [w-1, h-1],
[w//2, h-1], [0, h-1],
[0, h//2]
], dtype=np.float32)
return np.vstack([points, boundary_pts])
points_img1 = add_boundary_points(points_img1, width, height)
points_img2 = add_boundary_points(points_img2, width, height)
Compute the average shape of the landmarks, which will be used to compute a common triangulation for both images.
points_avg = (points_img1 + points_img2) / 2.0
Create a triangulation over the average points.
from scipy.spatial import Delaunay
tri = Delaunay(points_avg)
triangles = tri.simplices
These functions will handle the warping of triangle regions.
def apply_affine_transform(src, src_tri, dst_tri, size):
warp_mat = cv2.getAffineTransform(np.float32(src_tri), np.float32(dst_tri))
dst = cv2.warpAffine(src, warp_mat, (size[0], size[1]), None,
flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)
return dst
def morph_triangle(img1, img2, img, t1, t2, t, alpha):
# Bounding rectangles
r1 = cv2.boundingRect(np.float32([t1]))
r2 = cv2.boundingRect(np.float32([t2]))
r = cv2.boundingRect(np.float32([t]))
# Offset points by top-left corner
t1_rect = []
t2_rect = []
t_rect = []
for i in range(3):
t_rect.append(((t[i][0] - r[0]), (t[i][1] - r[1])))
t1_rect.append(((t1[i][0] - r1[0]), (t1[i][1] - r1[1])))
t2_rect.append(((t2[i][0] - r2[0]), (t2[i][1] - r2[1])))
# Get mask by filling triangle
mask = np.zeros((r[3], r[2], 3), dtype=np.float32)
cv2.fillConvexPoly(mask, np.int32(t_rect), (1.0, 1.0, 1.0), 16, 0)
# Warp patches
img1_rect = img1[r1[1]:r1[1]+r1[3], r1[0]:r1[0]+r1[2]]
img2_rect = img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]]
size = (r[2], r[3])
warp_img1 = apply_affine_transform(img1_rect, t1_rect, t_rect, size)
warp_img2 = apply_affine_transform(img2_rect, t2_rect, t_rect, size)
# Blend warped images
img_rect = (1.0 - alpha) * warp_img1 + alpha * warp_img2
# Copy blended triangle to output image
img[r[1]:r[1]+r[3], r[0]:r[0]+r[2]] = img[r[1]:r[1]+r[3], r[0]:r[0]+r[2]] * (1 - mask) + img_rect * mask
Create a function that morphs the two images by varying the alpha parameter from 0 to 1.
def morph_images(img1, img2, points1, points2, triangles, alpha):
# Compute weighted average points
points = (1 - alpha) * points1 + alpha * points2
# Create empty image
img_morphed = np.zeros(img1.shape, dtype=img1.dtype)
for tri_indices in triangles:
x, y, z = tri_indices
t1 = [points1[x], points1[y], points1[z]]
t2 = [points2[x], points2[y], points2[z]]
t = [points[x], points[y], points[z]]
morph_triangle(img1, img2, img_morphed, t1, t2, t, alpha)
return img_morphed
Create a sequence of frames by incrementally changing the alpha value.
num_frames = 20
frames = []
for i in range(num_frames + 1):
alpha = i / num_frames
morphed_frame = morph_images(img1, img2, points_img1, points_img2, triangles, alpha)
frames.append(morphed_frame)
import matplotlib.pyplot as plt
for frame in frames:
# Convert BGR to RGB for displaying correctly with matplotlib
frame_display = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
plt.imshow(frame_display)
plt.axis('off')
plt.show()
import imageio
# Convert frames to RGB
frames_rgb = [cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) for frame in frames]
# Save as GIF
imageio.mimsave('morph.gif', frames_rgb, fps=10)
out = cv2.VideoWriter('morph_video.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 10, (width, height))
for frame in frames:
out.write(frame)
out.release()
Automation for Non-Face Images: For images without faces, consider using feature matching algorithms like SIFT or ORB to automatically find corresponding points.
# Example using ORB
orb = cv2.ORB_create()
keypoints1, descriptors1 = orb.detectAndCompute(img1_gray, None)
keypoints2, descriptors2 = orb.detectAndCompute(img2_gray, None)
# Feature matching
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(descriptors1, descriptors2)
matches = sorted(matches, key=lambda x: x.distance)
# Extract matched points
points_img1 = np.float32([keypoints1[m.queryIdx].pt for m in matches])
points_img2 = np.float32([keypoints2[m.trainIdx].pt for m in matches])
Adjusting Number of Frames: Increase num_frames for a smoother transition.
Image Alignment: Pre-align images if necessary to improve morphing results.
Edge Handling: Pay special attention to edges and background to prevent artifacts.
Morphing images using Python involves careful alignment and blending of two images based on corresponding feature points. By following the steps outlined, you can create a smooth transition between any two images.
OpenCV Tutorials:
Image Processing Libraries:
Morphing Techniques:
For a complete working example and more advanced features, consider exploring these repositories:
Let me know if you have any questions or need further assistance with any of the steps!
Not yet included in a published release.