OpenCV 3 的一个功能 seamless cloning,能够将一个图像中的一个对象复制粘贴到另一个对象中,使其看起来自然。
例如,将一个飞机放在一张图中,如下图所示。看起来很不自然。

output = cv2.seamlessClone(src, dst, mask, center, flags)
src:将要被克隆到目标图上的原图,如例子中的飞机。
dst:目标图,如例子中的天空。
mask:想要克隆的目标图的mask。mask的大小要与原图大小一致。
center : 在目标图中原图的中心位置。
flags: cv2.NORMAL_CLONE and cv2.MIXED_CLONE.
output Output / result image.
import cv2
import numpy as np
# Read images : src image will be cloned into dst
im = cv2.imread("images/wood-texture.jpg")
obj= cv2.imread("images/iloveyouticket.jpg")
# Create an all white mask
mask = 255 * np.ones(obj.shape, obj.dtype)
# The location of the center of the src in the dst
width, height, channels = im.shape
center = (height/2, width/2)
# Seamlessly clone src into dst and put the results in output
normal_clone = cv2.seamlessClone(obj, im, mask, center, cv2.NORMAL_CLONE)
mixed_clone = cv2.seamlessClone(obj, im, mask, center, cv2.MIXED_CLONE)
# Write results
cv2.imwrite("images/opencv-normal-clone-example.jpg", normal_clone)
cv2.imwrite("images/opencv-mixed-clone-example.jpg", mixed_clone)


由结果可以看出,mixed_clone 边界更柔和。
例2.
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读取目标图和原图
im = cv2.imread("pick.jpg")
obj= cv2.imread("airplane.jpg")
# 创建全白的mask
mask = 255 * np.ones(obj.shape, obj.dtype)
# 定位所要放置原图的中心位置
width, height, channels = im.shape
center = (int(height/4), int(width/4))
# 克隆
normal_clone = cv2.seamlessClone(obj, im, mask, center, cv2.NORMAL_CLONE)
mixed_clone = cv2.seamlessClone(obj, im, mask, center, cv2.MIXED_CLONE)
fig = plt.figure(figsize=(30, 30))
plt.subplot(151), plt.imshow(im)
plt.subplot(152), plt.imshow(obj)
plt.subplot(153), plt.imshow(mask)
plt.subplot(154), plt.imshow(mixed_clone)
plt.subplot(154), plt.imshow(normal_clone)

网友评论