一. 情景引入
当我们要分析两张图片的关系,或者两张图片中特定区域的对应关系时,可用该方法。
可视化效果图如下:
二. 原理介绍与代码实现
原理:把两张图的像素映射到范围为[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)
运行上面的代码后,就会生成上面的分析结果图片。
每天进步一点,关注博主,下期更精彩!!!