week9-基于Homography的图像变换实现

主要实现在一张图片内,合理的插入绘制另一张图片。

效果如下:
在这里插入图片描述
原背景图如下:
在这里插入图片描述
插入的图片如下:
在这里插入图片描述

#!/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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值