Histogram matching of two images in Python 2.x?

后端 未结 3 598
星月不相逢
星月不相逢 2020-12-04 11:34

I\'m trying to match the histograms of two images (in MATLAB this could be done using imhistmatch). Is there an equivalent function available from a standard Python library

3条回答
  •  醉梦人生
    2020-12-04 12:26

    I would like to add a minor addition to both the solution written above. If somebody plans to make this as a global function (such as for grayscale images), it would be a good idea to convert the final matched array into its corresponding format (numpy.uint8). This might help in future image conversions without creating conflicts.

    def hist_norm(source, template):
    
        olddtype = source.dtype
        oldshape = source.shape
        source = source.ravel()
        template = template.ravel()
    
        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)
        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]
        interp_t_values = np.interp(s_quantiles, t_quantiles, t_values)
        interp_t_values = interp_t_values.astype(olddtype)
    
        return interp_t_values[bin_idx].reshape(oldshape)
    

提交回复
热议问题