在大图中插入小图:
import sys
import cv2
dir = sys.path[0]
small = cv2.imread(dir+'/small.png')
big = cv2.imread(dir+'/big.png')
x, y = 20, 20
h, w = small.shape[:2]
big[y:y+h, x:x+w] = small
cv2.imwrite(dir+'/out.png', big)
调整大小然后插入:
h, w = small.shape[:2]
small=cv2.resize(small,(w//2,h//2))
x, y = 20, 20
h, w = small.shape[:2]
big[y:y+h, x:x+w] = small
插入部分图像:
x, y = 20, 20
h, w = small.shape[:2]
hh, ww = h//2, w//2
big[y:y+hh, x:x+ww] = small[0:hh, 0:ww]
旋转样品:
bH, bW = big.shape[:2]
sH, sW = small.shape[:2]
ch, cw = sH//2, sW//2
x, y = sW-cw//2, ch
empty = 0 * np.ones((bH, bW, 3), dtype=np.uint8)
empty[y:y+sH, x:x+sW] = small
M = cv2.getRotationMatrix2D(center=(x+cw, y+ch), angle=45, scale=1)
rotated = cv2.warpAffine(empty, M, (bW, bH))
big[np.where(rotated != 0)] = rotated[np.where(rotated != 0)]
透视变换示例:
bH, bW = big.shape[:2]
sH, sW = small.shape[:2]
x, y = 0, 0
empty = 0 * np.ones((bH, bW, 3), dtype=np.uint8)
empty[y:y+sH, x:x+sW] = small
_inp = np.float32([[0, 0], [sW, 0], [bW, sH], [0, sH]])
_out = np.float32([[bW//2-sW//2, 0], [bW//2+sW//2, 0], [bW, bH], [0, bH]])
M = cv2.getPerspectiveTransform(_inp, _out)
transformed = cv2.warpPerspective(empty, M, (bH, bW))
big[np.where(transformed != 0)] = transformed[np.where(transformed != 0)]
最后用于映射坐标;我认为您只需要填写_out:
bH, bW = big.shape[:2]
sH, sW = small.shape[:2]
empty = 0 * np.ones((bH, bW, 3), dtype=np.uint8)
empty[:sH, :sW] = small
# Cordinates: TopLeft, TopRight, BottomRight, BottomLeft
_inp = np.float32([[0, 0], [sW, 0], [sW, sH], [0, sH]])
_out = np.float32([[50, 40], [300, 40], [200, 200], [10, 240]])
M = cv2.getPerspectiveTransform(_inp, _out)
transformed = cv2.warpPerspective(empty, M, (bH, bW))
big[np.where(transformed != 0)] = transformed[np.where(transformed != 0)]