使用OpenCV实现哈哈镜效果

使用OpenCV实现哈哈镜效果

导入工具包

import cv2
import numpy as np
import math
from vcam import vcam,meshGen
#导入python绘图matplotlib
import matplotlib.pyplot as plt
#使用ipython的魔法方法,将绘制出的图像直接嵌入在notebook单元格中
%matplotlib inline
#定义可视化图像函数
def look_img(img):
    '''opencv读入图像格式为BGR,matplotlib可视化格式为RGB,因此需将BGR转RGB'''
    img_RGB = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    plt.imshow(img_RGB)
    plt.show()

单张图片的镜子效果

file = "./data/test01.jpg"

for mode in range(8):
    # Reading the input image
    img = cv2.imread(file)
    img = cv2.resize(img,(300,300))
    H,W = img.shape[:2]
    # Creating the virtual camera object
    c1 = vcam(H=H,W=W)
    # Creating the surface object
    plane = meshGen(H,W)
    # We generate a mirror where for each 3D point, its Z coordinate is defined as Z = F(X,Y)
    if mode == 0:
        plane.Z += 20*np.exp(-0.5*((plane.X*1.0/plane.W)/0.1)**2)/(0.1*np.sqrt(2*np.pi))
    elif mode == 1:
        plane.Z += 20*np.exp(-0.5*((plane.Y*1.0/plane.H)/0.1)**2)/(0.1*np.sqrt(2*np.pi))
    elif mode == 2:
        plane.Z -= 10*np.exp(-0.5*((plane.X*1.0/plane.W)/0.1)**2)/(0.1*np.sqrt(2*np.pi))
    elif mode == 3:
        plane.Z -= 10*np.exp(-0.5*((plane.Y*1.0/plane.W)/0.1)**2)/(0.1*np.sqrt(2*np.pi))
    elif mode == 4:
        plane.Z += 20*np.sin(2*np.pi*((plane.X-plane.W/4.0)/plane.W)) + 20*np.sin(2*np.pi*((plane.Y-plane.H/4.0)/plane.H))
    elif mode == 5:
        plane.Z -= 20*np.sin(2*np.pi*((plane.X-plane.W/4.0)/plane.W)) - 20*np.sin(2*np.pi*((plane.Y-plane.H/4.0)/plane.H))
    elif mode == 6:
        plane.Z += 100*np.sqrt((plane.X*1.0/plane.W)**2+(plane.Y*1.0/plane.H)**2)
    elif mode == 7:
        plane.Z -= 100*np.sqrt((plane.X*1.0/plane.W)**2+(plane.Y*1.0/plane.H)**2)
    else:
        print("Wrong mode selected")
        exit(-1)
    # Extracting the generated 3D plane
    pts3d = plane.getPlane()
    # Projecting (Capturing) the plane in the virtual camera
    pts2d = c1.project(pts3d)
    # Deriving mapping functions for mesh based warping.
    map_x,map_y = c1.getMaps(pts2d)
    # Generating the output
    output = cv2.remap(img,map_x,map_y,interpolation=cv2.INTER_LINEAR)
    output = cv2.flip(output,1)
    #look_img(output)
    look_img(np.hstack((img,np.zeros((H,2,3),dtype=np.uint8),output)))

使用OpenCV实现哈哈镜效果_第1张图片
使用OpenCV实现哈哈镜效果_第2张图片
使用OpenCV实现哈哈镜效果_第3张图片
使用OpenCV实现哈哈镜效果_第4张图片
使用OpenCV实现哈哈镜效果_第5张图片使用OpenCV实现哈哈镜效果_第6张图片
使用OpenCV实现哈哈镜效果_第7张图片

使用OpenCV实现哈哈镜效果_第8张图片

你可能感兴趣的:(其他,opencv,python,计算机视觉)