# 不用PS 抠图，Python + OpenCV 自动实现海报场景替换！

• 确定至少四组对应点坐标

• 找到一个转换矩阵；

• 把找到的转换矩阵应用到 Moving Image 上，实现图像对齐；

$H = \left[ \begin{matrix} h_{00}& h_{01} & h_{02}\\ h_{10} & h_{11}&h_{12}\\ h_{20} & h_{21}&h_{22}\\ \end{matrix} \right]$
$A(x_1 ,y_1)$$A_1(x_2,y_2)$ 作为对应点，则 Homography $H$ 的的应用 如下：
$\left[ \begin{matrix} x_1\\ y_1\\ 1\\ \end{matrix} \right] = H\left[ \begin{matrix} x_2\\ y_2\\ 1\\ \end{matrix} \right] = \left[ \begin{matrix} h_{00} & h_{01} & h_{02}\\ h_{10} & h_{11} & h_{12}\\ h_{20} & h_{21} & h_{22}\\ \end{matrix} \right]\left[ \begin{matrix} x_2\\ y_2\\ 1\\ \end{matrix} \right]$

import cv2
import numpy as np

if __name__ =='__main__':

#图片读取
position_src = np.array([[141,131],[480,159],[493,630],[64,601]],dtype = float)

position_dst = np.array([[318,256],[543,372],[316,670],[73,473]],dtype = float)

#计算转换矩阵
h,status = cv2.findHomography(position_src,position_dst)

#对图片进行仿射变换
out_img = cv2.warpPerspective(img_src,h,(img_dst.shape[1],img_dst.shape[0]))

#Display images;
cv2.imshow("Source image",img_src)
cv2.imshow("Destination Image",img_dst)
cv2.imshow("Warped Source Image",out_img)

cv2.waitKey(0)


def mouse_handler(event,x,y,flags,data):
if event ==cv2.EVENT_LBUTTONDOWN:
cv2.circle(data['im'],(x,y),3,(0,0,255),5,16)
cv2.namedWindow("Image",0)
cv2.imshow("Image",data['im'])
if len(data['points']) <4:
data['points'].append([x,y])

def get_four_points(im):

data = {}
data['im'] = im.copy()
data['points'] = []
# Set the callback function for any mouse event
cv2.namedWindow("Image", 0)
cv2.imshow('Image',im)
#请注意你标记点的数据，是顺时针，需要与pst_src 方向一致
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__':

size = img_src.shape
# 取得四个坐标
pst_src = np.array(
[
[0,0],[size[1]-1,0],
[size[1]-1,size[0]-1],
[0,size[0]-1]
],dtype=float
)

print("Click on four corners of bllboard and the press ENTER")
four_point  = get_four_points(img_dst)

# Calculate  Homography between  source and destination points
h,status = cv2.findHomography(pst_src,four_point)

im_temp = cv2.warpPerspective(img_src,h,(img_dst.shape[1],img_dst.shape[0]))

cv2.fillConvexPoly(img_dst,four_point.astype(int),0,16)

#add wraped source image to destination image

img_dst = img_dst + im_temp
cv2.namedWindow("Image", 0)
cv2.imshow("Image",img_dst)
cv2.waitKey(0)


08-04 4万+

07-16 2万+

07-24 4494

02-20 7051

04-24 67

08-10 4895

05-02 48

08-03

09-10 138

03-01 539

12-21 1万+

11-06 316

07-19 612

09-29 323

03-30 93

12-13 2616

06-27 2067

12-12 1486

04-21 2496

03-18 31

#### PS快速秒抠图技巧

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客