<p>根据我前面的答案的评论,这里有一个简单的缩放和平移仿射扭曲的方法。你知道吗</p>
<pre><code>Read both images
Measure the height of the green region and get the height of the src image
Measure the center (x,y) of the green region and get the center of the src image
Compute the affine matrix coefficients for scale and translation only (no rotation or skew)
Warp the source image using the affine matrix the background will be black
Create a binary mask from the warped src image making everything not black into white
Invert the mask
Apply the inverted mask to the dst image
Add the warped src over the masked dst to form the result
</code></pre>
<p><br/>
src公司:</p>
<p><a href="https://i.stack.imgur.com/xq9ZA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xq9ZA.jpg" alt="enter image description here"/></a></p>
<p>夏令时:</p>
<p><a href="https://i.stack.imgur.com/1Cftm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Cftm.png" alt="enter image description here"/></a></p>
<pre><code>#!/python3.7
import cv2
import numpy as np
# Read source image.
src = cv2.imread('original.jpg')
h_src, w_src = src.shape[:2]
# Read destination image.
dst = cv2.imread('green_rect.png')
h_dst, w_dst = dst.shape[:2]
# compute scale from height of src and height of green region
h_green=170
scale = h_green/h_src
# compute offsets from center of scaled src and center of green
x_src = (scale)*w_src/2
y_src = (scale)*h_src/2
x_green = 165
y_green = 140
xoff = (x_green - x_src)
yoff = (y_green - y_src)
# build affine matrix for scale and translate only
affine_matrix = np.float32([ [scale,0,xoff], [0,scale,yoff] ])
# do affine warp
# add 1 to src to ensure no pure black
src_warped = cv2.warpAffine(src+1, affine_matrix, (w_dst, h_dst), cv2.INTER_AREA)
# Compute mask (roi) in warped src
_, mask = cv2.threshold(src_warped,1,255,cv2.THRESH_BINARY)
# Invert single channel of mask
inv_mask = cv2.bitwise_not(mask[:,:,0])
# Mask dst with inverted mask
dst_masked = cv2.bitwise_and(dst, dst, mask=inv_mask)
# Put warped src over masked dst
result = cv2.add(dst_masked,src_warped)
# Save outputs
cv2.imwrite('warped_src.jpg', src_warped)
cv2.imwrite('masked_src.jpg', mask)
cv2.imwrite('affine_composite.jpg', result)
</code></pre>
<p><br/>
翘曲钢筋:</p>
<p><a href="https://i.stack.imgur.com/nTUMr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nTUMr.jpg" alt="enter image description here"/></a></p>
<p>反转遮罩:</p>
<p><a href="https://i.stack.imgur.com/5a5TJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5a5TJ.jpg" alt="enter image description here"/></a></p>
<p>屏蔽dst</p>
<p><a href="https://i.stack.imgur.com/zfSiv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zfSiv.jpg" alt="enter image description here"/></a></p>
<p>结果:</p>
<p><a href="https://i.stack.imgur.com/dtfDB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dtfDB.jpg" alt="enter image description here"/></a></p>