python opencv图像匹配,匹配两个图像的中心(OpenCV,Python)

I asked before a question which was, maybe, too complex. So here I am with a new one a little bit simplier.

I have two images:

What I want to do is to center the second image into the center of the first, like below.

What I achieved until now was the center of these images.

The value is a list of two points, X-Y.

How can I match these points to have a result like desired above ?

import cv2

import numpy as np

import os

img1 = cv2.imread(os.path.expanduser('~\\Desktop\\c1.png'))

# ---Read image and obtain threshold---

img0 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img0, 120, 255, 1)

# ---Obtain contours---

image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

cnts = contours

center = []

for c in cnts:

M = cv2.moments(c)

cX = int(M["m10"] / M["m00"])

cY = int(M["m01"] / M["m00"])

print(cX, cY)

center.append(cX)

center.append(cY)

print(center)

Thanks

解决方案

Here is my step:

Find centers by contours

Calc the offset between centers

Do slice-op to paste the object image

For those two image:

1fFjnRC.jpg

dJZlt3M.jpg

This is my result (with 0.3x for img2):

zsHM9.png

#!/usr/bin/python3

# 2018.01.16 21:07:48 CST

# 2018.01.16 21:23:47 CST

import cv2

import numpy as np

import os

def findCenter(img):

print(img.shape, img.dtype)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)

#cv2.imshow("threshed", threshed);cv2.waitKey();cv2.destroyAllWindows()

#_, cnts, hierarchy = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

M = cv2.moments(cnts[0])

cX = int(M["m10"] / M["m00"])

cY = int(M["m01"] / M["m00"])

return (cX,cY)

img1 = cv2.imread("img1.jpg")

img2 = cv2.resize(cv2.imread("img2.jpg"), None, fx=0.3, fy=0.3)

## (1) Find centers

pt1 = findCenter(img1)

pt2 = findCenter(img2)

## (2) Calc offset

dx = pt1[0] - pt2[0]

dy = pt1[1] - pt2[1]

## (3) do slice-op `paste`

h,w = img2.shape[:2]

dst = img1.copy()

dst[dy:dy+h, dx:dx+w] = img2

cv2.imwrite("res.png", dst)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值