匹配两个图像的中心(OpenCV,Python) [英] Match center of two images (OpenCV, Python)

查看:381
本文介绍了匹配两个图像的中心(OpenCV,Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问过一个可能太复杂的问题.所以在这里,我有了一个新的简单点.

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

我有两张图片:

图片1 图片2

我要做的是将第二个图像居中放置在第一个图像的中央,如下所示.

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.

值是X-Y两点的列表.

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)

谢谢

推荐答案

这是我的步骤:

  1. 通过轮廓查找中心
  2. 计算中心之间的偏移量
  3. paste对象图像进行切片操作
  1. Find centers by contours
  2. Calc the offset between centers
  3. Do slice-op to paste the object image

对于这两个图像:

这是我的结果(img2为0.3x):

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

#!/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)

这篇关于匹配两个图像的中心(OpenCV,Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆