python - 图像进入空白图像中心的时刻(Python、OpenCV)

标签 python opencv

这是我的问题。 我尝试复制此图像 (20x20): enter image description here到一个由代码(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)

这是输出:enter image description here

你怎么看不完美,右边有一些白色,给我带来了一些问题,我知道问题出在“掩码”上,我尝试修改它,但是当我改变一件事时,代码没有不工作。 你知道其他方法来做同样的想法,或者我只需要修改它。

期望的输出应该像这个例子enter image description here , 根据请求居中。

谢谢

最佳答案

这不是我的代码,我在另一个问题中发现了它,我尝试了一下并且工作得很好。 这是代码:

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)

这是原答案: Match center of two images (OpenCV, Python)

关于python - 图像进入空白图像中心的时刻(Python、OpenCV),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48279081/

相关文章:

python - InternalError : (1366, u“整数值不正确:选择)错误

python - 将新行添加到 Pandas 数据框

python - 根据条件更改 tensorflow 张量的值

python - ImportError : DLL load failed: %1 is not a valid Win32 application. 但是DLL在那里

c++ - 如何将这个用于 OpenCV 的 MatExpr 的 C 包装器的指针输出转换回 MatExpr

c++ - 使用 Opencv 和 Qt 对两个灰度图像进行减法的使用条款

image - 检测噪声图像中的弱 Blob

python - 使用 usecols 时 pandas.read_excel 错误

python - 使用 Python 库的多元多重回归

python - 如何消除光的偏转