简体   繁体   中英

Moment of image into center of blank image (Python, OpenCV)

This is my problem. I try to copy this image (20x20): 在此处输入图片说明 into a new one created by code (28x28 blank canvas) with precise position. What I am trying to do is to set the violet point of source image centered into a new (canvas) image. This is my code to do it:

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)

and this is the output : 在此处输入图片说明

How do you see is not perfect there is some white in the right part and cause me some problems, i know the problem is the "mask", i try to modify it, but when i change 1 thing the code doesn't work. Do you know other ways to do the same think or maybe i only need to modify this.

Desired output should be like this example 在此处输入图片说明 , centered according the reequest.

Thanks

this is not my code, i found it into another question, i try it and work very well. This is the code:

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)

This is the original answer: Match center of two images (OpenCV, Python)

Here is my result using numpy and OpenCV:

  1. Find the coords in object
  2. Calc the moment center of the object's coords
  3. Calc the moment center offset (from src to dst)
  4. Adjust the coord with offset
  5. Do slice op

The result:

(1) object :

在此处输入图片说明

(2) cross background:

在此处输入图片说明

(3) object on the cross background:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM