这是我的问题。 我尝试复制此图像 (20x20): 到一个由代码(28x28 空白 Canvas )创建的具有精确位置的新 Canvas 中。我想要做的是将源图像的紫色点设置为新( Canvas )图像的中心。 这是我的代码:
import cv2
import numpy as np
import os
# Read images : src image will be cloned into dst
im = cv2.imread(os.path.expanduser('~\\Desktop\\cube.png'))
obj = cv2.imread(os.path.expanduser('~\\Desktop\\testCV.png'))
# Create an all white mask
mask = 255 * np.ones(obj.shape, obj.dtype)
# The location of the center of the src in the dst
center = (int(10), int(13))
# Seamlessly clone src into dst and put the results in output
normal_clone = cv2.seamlessClone(obj, im, mask, center, cv2.NORMAL_CLONE)
# Write results
cv2.imwrite(os.path.expanduser('~\\Desktop\\fin.png'), normal_clone)
你怎么看不完美,右边有一些白色,给我带来了一些问题,我知道问题出在“掩码”上,我尝试修改它,但是当我改变一件事时,代码没有不工作。 你知道其他方法来做同样的想法,或者我只需要修改它。
谢谢
最佳答案
这不是我的代码,我在另一个问题中发现了它,我尝试了一下并且工作得很好。 这是代码:
import cv2
import os
import numpy as np
def findCenter(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
_, cnts, hierarchy = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
M = cv2.moments(cnts[0])
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
return (cX, cY)
img1 = cv2.imread("Path of the image you want to copy")
img2 = cv2.imread("Path of the image you want to use like a backgroud")
pt1 = findCenter(img1)
pt2 = findCenter(img2)
## (2) Calc offset
dx = (pt1[0] - pt2[0])
dy = (pt1[1] - pt2[1])
h, w = img2.shape[:2]
dst = img1.copy()
dst[dy:dy + h, dx:dx + w] = img2
cv2.imwrite(path + roi, dst)
关于python - 图像进入空白图像中心的时刻(Python、OpenCV),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48279081/