如何分析两张图片的对应关系?

一. 情景引入

当我们要分析两张图片的关系,或者两张图片中特定区域的对应关系时,可用该方法。
可视化效果图如下:在这里插入图片描述

二. 原理介绍与代码实现

原理:把两张图的像素映射到范围为[0,1]的区间,以第一张图的像素值为x坐标,另一张图的像素值为y坐标,从而组成平面中的点,将这些点显示在幕布中就是上面的效果。由于图片一般有三个通道(BGR),所以用三种不同颜色的点表示,三种颜色的点表示每个通道的关系。
我们分析下面两张图的关系:
在这里插入图片描述
在这里插入图片描述

import math
import cv2
import numpy as np


def draw_axis(image):
    white_color = (255, 255, 255)
    w, h = image.shape[1], image.shape[0]
    cv2.line(image, (0, 0), (0, h), white_color, thickness=3)
    cv2.line(image, (0, h), (w, h), white_color, thickness=3)
    axis_height = 8
    xs = (np.linspace(0, 1, 11) * (w - 1)).astype(np.int32)
    for x in xs:
        cv2.line(image, (x, h-1), (x, h-1-axis_height), white_color, thickness=3)

    ys = (np.linspace(0, 1, 11) * (h - 1)).astype(np.int32)
    for y in ys:
        cv2.line(image, (0, y), (axis_height, y), white_color, thickness=3)
    return image


def draw_coord(image, x, y, show_cn=None):
    if show_cn is None:
        show_cn = [0, 1, 2]
    elif not isinstance(show_cn,(tuple,list)):
        show_cn = [show_cn]

    if x.ndim == 3:
        x = np.reshape(x, (-1, x.shape[-1]))

    if y.ndim == 3:
        y = np.reshape(y, (-1, y.shape[-1]))

    bgr_colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
    min_color = 80
    max_color = 255

    w, h = image.shape[1], image.shape[0]
    image = draw_axis(image)
    for cn in show_cn:
        points = {}
        for px, py in zip(x[:, cn], y[:, cn]):
            point = (int(round(px * (w-1))), int(round((1 - py) * (h-1))))
            points.setdefault(point, 0)
            points[point] += 1
        point_nums = [num for num in points.values()]
        min_point_nums = np.min(point_nums)
        max_point_nums = np.max(point_nums)
        for point, num in points.items():
            color = min_color + (max_color - min_color) * (num - min_point_nums) / (max_point_nums - min_point_nums)
            color = np.array(bgr_colors)[cn] * color
            color = np.clip(color, 0, 255)
            cv2.circle(image, point, 1, color.tolist(), -1)

    cv2.imwrite("analysis_result.jpg", image)


if __name__ == "__main__":
    img1 = cv2.imread("img1.png")
    img1 = cv2.resize(img1, (512, 512))

    img2 = cv2.imread("img2.png")
    img2 = cv2.resize(img2, (512,512))

    x = img1.astype(np.float32) / 255
    y = img2.astype(np.float32) / 255
    coord_img = np.zeros_like(img1)
    draw_coord(coord_img, x, y)

运行上面的代码后,就会生成上面的分析结果图片。

每天进步一点,关注博主,下期更精彩!!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值