微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

与matlab里面 imadjust 函数相同的python代码

          正在做一个把matlab程序转python的工作,遇到 matlab里面的 imadjust 函数,但是找了一圈没有对应的python函数,需要自定义一个函数

import numpy as np
from bisect import bisect_left

 # 已测试完毕,成功
    def imadjust(src, tol=1, vin=[0, 255], vout=(0, 255)):
        # src : input one-layer image (numpy array)
        # tol : tolerance, from 0 to 100.
        # vin  : src image bounds
        # vout : dst image bounds
        # return : output img
        assert len(src.shape) == 2, 'Input image should be 2-dims'
        tol = max(0, min(100, tol))
        if tol > 0:
            # Compute in and out limits
            # Histogram
            hist = np.histogram(src, bins=list(range(256)), range=(0, 255))[0]
            # Cumulative histogram
            cum = hist.copy()
            for i in range(1, 255): cum[i] = cum[i - 1] + hist[i]
            # Compute bounds
            total = src.shape[0] * src.shape[1]
            low_bound = total * tol / 100
            upp_bound = total * (100 - tol) / 100
            vin[0] = bisect_left(cum, low_bound)
            vin[1] = bisect_left(cum, upp_bound)
        # Stretching
        scale = (vout[1] - vout[0]) / (vin[1] - vin[0])
        vs = src - vin[0]
        vs[src < vin[0]] = 0
        vd = vs * scale + 0.5 + vout[0]
        vd[vd > vout[1]] = vout[1]
        dst = vd
        return dst

          src是一个二维矩阵,数据类型为uint8(0-255,用来表示灰度值),测试结果和matlab基本一模一样。做到了同输入同输出

          用到了 bisect_left 它的用法可以参考 python:从整数列表(数组)中获取最接近给定值的数字

          当然,最好看文档 bisect — 数组二分查找算法,讲的比较好

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐