How to replace a contour (rectangle) in an image with a new image using Python?

一个人想着一个人 提交于 2019-12-06 08:10:13

I downloaded your image data and reproduced the problem in my local machine to find out the solution. Also downloaded lenna.png to fit inside the phone screen.

import cv2
import numpy as np

# Template image of iPhone
img1 = cv2.imread("/Users/anmoluppal/Downloads/46F1U.jpg")
# Sample image to be used for fitting into white cavity
img2 = cv2.imread("/Users/anmoluppal/Downloads/Lenna.png")

rows,cols,ch = img1.shape

# Hard coded the 3 corner points of white cavity labelled with green rect.
pts1 = np.float32([[201, 561], [455, 279], [742, 985]])
# Hard coded the same points on the reference image to be fitted.
pts2 = np.float32([[0, 0], [512, 0], [0, 512]])

# Getting affine transformation form sample image to template.
M = cv2.getAffineTransform(pts2,pts1)

# Applying the transformation, mind the (cols,rows) passed, these define the final dimensions of output after Transformation.
dst = cv2.warpAffine(img2,M,(cols,rows))

# Just for Debugging the output.
final = cv2.addWeighted(dst, 0.5, img1, 0.5, 1)
cv2.imwrite("./garbage.png", final)

You can overlay the new image (rotated to screen orientation of the phone) on to the original image by

import cv2
A_img = cv2.imread("new_image.png")
B_img = cv2.imread("larger_image.jpg")
x_offset=y_offset=50
B_img[y_offset:y_offset+A_img.shape[0], x_offset:x_offset+A_img.shape[1]] = A_img

You can have the new image appropriately rotated with alpha channel if required.

As you mentioned in the comment below (under the heading perspective transformation) the new image need to be perspective transformed (distorted). Look in the link below for how perspective transformation works to fix the distorted image to straight (you want the reverse of this).

http://docs.opencv.org/master/da/d6e/tutorial_py_geometric_transformations.html#gsc.tab=0

You basically need to provide 4 points in the original and distorted space (pts1 and pts2) for the transformation.

I think you might be able to use the four corners of the original image to be inserted (pts1) and the corners of contours (pts2) should work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!