如何访问 cv2.matchTemplate 函数的部分内容以正确调整输入图像的强度和对比度

问题描述 投票:0回答:1

我正在尝试使用 cv2.matchTemplate 进行模板图像匹配。然而,由于闪电条件,与我的模板相比,我的图像在强度和对比度方面发生了变化(它们是在不同时刻拍摄的)。

我创建了一个函数,可以根据整个模板对比度和强度调整图像对比度和强度。

def match_contrast_and_brightness(image1, image2):
    # further optimization possible
    img1 = image1.astype(np.float32)
    img2 = image2.astype(np.float32)

    mean1, mean2 = np.mean(img1, axis=(0, 1)), np.mean(img2, axis=(0, 1))
    std1, std2 = np.std(img1, axis=(0, 1)), np.std(img2, axis=(0, 1))

    alpha = std2 / std1
    beta = mean2 - alpha * mean1

    adjusted_image = np.clip(alpha * image1 + beta, 0, 255).astype(np.uint8)

    return adjusted_image

但是,这种方法不够稳健,特别是当模板非常大并且包含附加信息时。

我想到的最好的想法是根据每个位置/窗口调整对比度和强度,matchTemplate 函数正在搜索。例如,如果它开始在模板的左上角部分进行搜索,我想根据模板的左上角部分转换我的图像,然后测量相似度,然后转到下一个位置并执行相同的操作等等..

为此,我需要修改 matchTemplate 函数并提取每个位置的强度和对比度(或不提取?)。我怎样才能做到这一点?

我找到了c++中该函数的链接这里

Ps:我尝试了灰度、hsv、lab、r、g、b、h、s、v、l、a 和 b 通道和格式,但我仍然不在那里。

python opencv colors match template-matching
1个回答
0
投票
import numpy as np

def match_contrast_and_brightness(image1, image2): # 确保图像是 float32 img1 = image1.astype(np.float32) img2 = image2.astype(np.float32)

# Normalize images
img1_normalized = (img1 - np.mean(img1, axis=(0, 1))) / np.std(img1, axis=(0, 1))
img2_normalized = (img2 - np.mean(img2, axis=(0, 1))) / np.std(img2, axis=(0, 1))

# Compute per-channel mean and std
mean1, mean2 = np.mean(img1_normalized, axis=(0, 1)), np.mean(img2_normalized, axis=(0, 1))
std1, std2 = np.std(img1_normalized, axis=(0, 1)), np.std(img2_normalized, axis=(0, 1))

# Compute alpha and beta for each channel
alpha = std2 / std1
beta = mean2 - alpha * mean1

# Adjust image contrast and brightness
adjusted_image = np.clip(alpha * img1 + beta, 0, 255.0)

# Convert back to uint8 after clipping
adjusted_image = adjusted_image.astype(np.uint8)

return adjusted_image

此版本的函数应正确处理灰度和彩色图像。此外,它会在计算平均值和标准差之前对图像进行归一化,以便在不同图像上实现更稳健的性能。

© www.soinside.com 2019 - 2024. All rights reserved.