Skip to content

Instantly share code, notes, and snippets.

@simon-donike
Last active August 9, 2023 11:03
Show Gist options
  • Save simon-donike/2e4046a52cafaef8ecf3526673bcc346 to your computer and use it in GitHub Desktop.
Save simon-donike/2e4046a52cafaef8ecf3526673bcc346 to your computer and use it in GitHub Desktop.
MinMax and percentile MinMax stretching for numpy arrays
# for np arrays
import numpy as np
def minmax(img):
return(img-np.min(img) ) / (np.max(img)-np.min(img))
import numpy as np
def minmax_percentile(img,perc=2):
lower = np.percentile(img,perc)
upper = np.percentile(img,100-perc)
img[img>upper] = upper
img[img<lower] = lower
return(img-np.min(img) ) / (np.max(img)-np.min(img))
# for tensors
import torch
def minmax_percentile(img, perc=2):
lower = torch.kthvalue(img.flatten(), int(len(img.flatten()) * perc / 100)).values
upper = torch.kthvalue(img.flatten(), int(len(img.flatten()) * (100 - perc) / 100)).values
img = torch.where(img > upper, upper, img)
img = torch.where(img < lower, lower, img)
return (img - torch.min(img)) / (torch.max(img) - torch.min(img))
import torch
def minmax(img):
return (img - torch.min(img)) / (torch.max(img) - torch.min(img))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment