正在做一个把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 — 数组二分查找算法,讲的比较好