主要实现在一张图片内,合理的插入绘制另一张图片。
效果如下:
原背景图如下:
插入的图片如下:
#!/usr/bin/env python
import cv2
import numpy as np
#from utils import get_four_points
import sys
def get_four_points(im):
#记录鼠标在图片上点的四个点,并且返回数组。
# Set up data to send to mouse handler
data = {}
data['im'] = im.copy()
data['points'] = []
#Set the callback function for any mouse event使用鼠标回调函数
cv2.imshow("Image",im)
cv2.setMouseCallback("Image", mouse_handler, data)
cv2.waitKey(0)
# Convert array to np.array
points = np.vstack(data['points']).astype(float)
return points
if __name__ == '__main__' :
# Read source image.
im_src = cv2.imread('ccrabbit.jpg');
size = im_src.shape
# Create a vector of source points.
pts_src = np.array(
[
[0,0],
[size[1] - 1, 0],
[size[1] - 1, size[0] -1],
[0, size[0] - 1 ]
],dtype=float
);
# Read destination image设置背景图
im_dst = cv2.imread('times-square.jpg');
# Get four corners of the billboard
print ('Click on four corners of a billboard and then press ENTER')
pts_dst = get_four_points(im_dst)
# Calculate Homography between source and destination points计算单应性矩阵
h, status = cv2.findHomography(pts_src, pts_dst);
# Warp source image 透视变换
im_temp = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
cv2.fillConvexPoly
使用绘图函数来把 im_src重新绘制在背景图上。cv2.fillConvexPoly()函数可以用来填充凸多边形,只需要提供凸多边形的顶点即可.凸多边形的顶点矩阵已经通过上面手动描点返回。
# Black out polygonal area in destination image.绘图函数
cv2.fillConvexPoly(im_dst, pts_dst.astype(int), 0, 16);
# Add warped source image to destination image.
im_dst = im_dst + im_temp;
# Display image.
cv2.imshow("Image", im_dst);
cv2.waitKey(0);