Python 2.x 中两个图像的直方图匹配?

2024-02-07

我正在尝试匹配两个图像的直方图(在 MATLAB 中,这可以使用imhistmatch http://www.mathworks.com/help/images/ref/imhistmatch.html)。标准 Python 库中是否有等效的函数?我看过 OpenCV、scipy 和 numpy,但没有看到任何类似的功能。


我之前写过一个答案here https://stackoverflow.com/a/31493356/1461210解释如何对图像直方图进行分段线性插值,以强制执行高光/中间调/阴影的特定比率。

相同的基本原则直方图匹配 https://en.wikipedia.org/wiki/Histogram_matching两个图像之间。本质上,您计算源图像和模板图像的累积直方图,然后进行线性插值以查找模板图像中与源图像中唯一像素值的分位数最接近的唯一像素值:

import numpy as np

def hist_match(source, template):
    """
    Adjust the pixel values of a grayscale image such that its histogram
    matches that of a target image

    Arguments:
    -----------
        source: np.ndarray
            Image to transform; the histogram is computed over the flattened
            array
        template: np.ndarray
            Template image; can have different dimensions to source
    Returns:
    -----------
        matched: np.ndarray
            The transformed output image
    """

    oldshape = source.shape
    source = source.ravel()
    template = template.ravel()

    # get the set of unique pixel values and their corresponding indices and
    # counts
    s_values, bin_idx, s_counts = np.unique(source, return_inverse=True,
                                            return_counts=True)
    t_values, t_counts = np.unique(template, return_counts=True)

    # take the cumsum of the counts and normalize by the number of pixels to
    # get the empirical cumulative distribution functions for the source and
    # template images (maps pixel value --> quantile)
    s_quantiles = np.cumsum(s_counts).astype(np.float64)
    s_quantiles /= s_quantiles[-1]
    t_quantiles = np.cumsum(t_counts).astype(np.float64)
    t_quantiles /= t_quantiles[-1]

    # interpolate linearly to find the pixel values in the template image
    # that correspond most closely to the quantiles in the source image
    interp_t_values = np.interp(s_quantiles, t_quantiles, t_values)

    return interp_t_values[bin_idx].reshape(oldshape)

例如:

from matplotlib import pyplot as plt
from scipy.misc import lena, ascent

source = lena()
template = ascent()
matched = hist_match(source, template)

def ecdf(x):
    """convenience function for computing the empirical CDF"""
    vals, counts = np.unique(x, return_counts=True)
    ecdf = np.cumsum(counts).astype(np.float64)
    ecdf /= ecdf[-1]
    return vals, ecdf

x1, y1 = ecdf(source.ravel())
x2, y2 = ecdf(template.ravel())
x3, y3 = ecdf(matched.ravel())

fig = plt.figure()
gs = plt.GridSpec(2, 3)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1], sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(gs[0, 2], sharex=ax1, sharey=ax1)
ax4 = fig.add_subplot(gs[1, :])
for aa in (ax1, ax2, ax3):
    aa.set_axis_off()

ax1.imshow(source, cmap=plt.cm.gray)
ax1.set_title('Source')
ax2.imshow(template, cmap=plt.cm.gray)
ax2.set_title('template')
ax3.imshow(matched, cmap=plt.cm.gray)
ax3.set_title('Matched')

ax4.plot(x1, y1 * 100, '-r', lw=3, label='Source')
ax4.plot(x2, y2 * 100, '-k', lw=3, label='Template')
ax4.plot(x3, y3 * 100, '--r', lw=3, label='Matched')
ax4.set_xlim(x1[0], x1[-1])
ax4.set_xlabel('Pixel value')
ax4.set_ylabel('Cumulative %')
ax4.legend(loc=5)

对于一对 RGB 图像,您可以将此函数单独应用于每个通道。根据您想要实现的效果,您可能需要首先将图像转换为不同的色彩空间。例如,您可以转换为HSV空间 https://i.stack.imgur.com/GWtt1.jpg然后,如果您想匹配亮度,而不是色调或饱和度,则仅在 V 通道上进行匹配。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 2.x 中两个图像的直方图匹配? 的相关文章

  • 使用 Pillow 和 Numpy 进行图像推导

    I have two images and 我想导出一个只有红色 Hello 的图像 例如 所以我正在运行一个简单的推导python脚本 from PIL import Image import numpy as np root root
  • xlrd 读取 xls XLRDError:不支持的格式或损坏的文件:预期的 BOF 记录;找到“\r\n”

    这是代码 xls open workbook data xls 作为回报 File home woles P2 fin fin apps data container importer py line 16 in import data x
  • sphinx 中的分组方法文档字符串

    是否可以使用 sphinx 的 autodoc 功能将多个方法文档字符串分组 以便将它们列在一起 class Test object def a self A method of group foo def b self A method
  • HoughLinesP后如何合并线?

    My task is to find coordinates of lines startX startY endX endY and rectangles 4 lines Here is input file 我使用下一个代码 img c
  • 如何在不破坏默认行为的情况下覆盖 __getattr__ ?

    我如何覆盖 getattr https docs python org 3 reference datamodel html object getattr 类的方法而不破坏默认行为 压倒一切 getattr 应该没事 getattr 仅作为
  • Python pandas:删除字符串中分隔符之后的所有内容

    我有数据框 其中包含例如 vendor a ProductA vendor b ProductA vendor a Productb 我需要删除所有内容 包括 两个 以便我最终得到 vendor a vendor b vendor a 我尝
  • SQLAlchemy:检查给定值是否在列表中

    问题 在 PostgreSQL 中 检查某个字段是否在给定列表中是使用IN操作员 SELECT FROM stars WHERE star type IN Nova Planet SQLAlchemy 的等价物是什么INSQL查询 我尝试过
  • 如何充分释放函数中使用的GPU内存

    我在用着cupy在接收一个函数numpy数组 将其推到 GPU 上 对其进行一些操作并返回cp asnumpy它的副本 问题 函数执行后内存没有被释放 如ndidia smi 我知道内存的缓存和重用cupy 但是 这似乎仅适用于每个用户 当
  • Highcharts 奇怪的分组行为

    我正在使用延迟加载 http www highcharts com stock demo lazy loading加载 OHLC 数据的方法 在服务器端 我使用 Python MySQL 并有 4 个包含 OHLC 数据的表 时间间隔为 5
  • 使用Python进行图像识别[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我有一个想法 就是我想识别图像中的字母 可能是 bmp或 jpg 例如 这是一个包含字母 S 的 bmp 图像 我想做的是使用Pyth
  • 使用 OpenCV 进行相机校准 - 如何调整棋盘方块大小?

    我正在使用 OpenCV Python 示例开发相机校准程序 来自 OpenCV 教程 http opencv python tutroals readthedocs io en latest py tutorials py calib3d
  • 比较两个文本文件并计算差异

    我一直在尝试在Python中比较两个文本文件 本质上我想打开它们并一次比较一个字符 如果字符不同 则向计数器添加1 然后显示该值 这是我到目前为止所拥有的 usr bin env python diff 0 import random im
  • 将查询参数添加到 URL

    我正在尝试自动从网站下载数据 我需要将动态参数传递到每天更改的站点 html 的结构是表格而不是表单 如何传递参数并从 url 获取结果 这是我尝试过的 它需要在 python 2 7 中 import urllib url https d
  • Bottle 是否可以处理没有并发的请求?

    起初 我认为 Bottle 会并发处理请求 所以我编写了如下测试代码 import json from bottle import Bottle run request response get post import time app B
  • 使用 .map() 在 pandas DataFrame 中高效创建附加列

    我正在分析形状与以下示例类似的数据集 我有两种不同类型的数据 abc数据和xyz data abc1 abc2 abc3 xyz1 xyz2 xyz3 0 1 2 2 2 1 2 1 2 1 1 2 1 1 2 2 2 1 2 2 2 3
  • 为什么 tesseract 无法从这个简单的图像中读取文本?

    我在 pytesseract 上阅读了大量的帖子 但我无法让它从一个简单的图像中读取文本 它返回一个空字符串 这是图像 我尝试过缩放它 灰度化它 调整对比度 阈值 模糊 以及其他帖子中所说的一切 但我的问题是我不知道 OCR 想要更好地工作
  • 在Python中打开网站框架或图像

    所以我对 python 相当熟练 并且经常使用 urllib2 和 Cookies 来实现网站自动化 我刚刚偶然发现了 webbrowser 模块 它可以在默认浏览器中打开一个网址 我想知道是否可以从该 url 中仅选择一个对象并打开它 具
  • Python 可以替代 Java 小程序吗?

    除了制作用于物理模拟 如抛射运动 重力等 的教育性 Java 小程序之外 还有其他选择吗 如果你想让它在浏览器中运行 你可以使用PyJamas http pyjs org 这是一个 Python 到 Javascript 的编译器和工具集
  • Matlab下降低图像质量

    问候 我正在尝试找到一种简单的方法来处理图像 以便将其质量从 8 位降低到 3 位 实现这一目标的最简单方法是什么 干杯 如果要线性缩放 只需将每个像素值除以 255 7 即 如果原始图像存储在矩阵 I 中 则让低分辨率图像 J I 255
  • Matplotlib 渲染日期、图像的问题

    我在使用 conda forge 的 Matplotlib v 3 1 3 和 python 3 7 时遇到问题 我拥有 Matplotlib 所需的所有依赖项 当我输入这段代码时 它应该可以工作 我得到了泼溅艺术 它基于此 YouTube

随机推荐