albumentations

AutoContrast in Albumentations?


Can I use AutoContrast in Albumentations library? That is, making the darkest pixel black and lightest pixel white. I see the RandomBrightnessContrast one, but is it the right one when I select contrast parameter to 0?


Solution

  • Unfortunately, there is no ready-to-use transform for autocontrast now. You may implement it by yourself using Lambda transform:

    def _autocontrast(img):
        h = cv2.calcHist([img], [0], None, [256], (0, 256)).ravel()
    
        for lo in range(256):
            if h[lo]:
                break
        for hi in range(255, -1, -1):
            if h[hi]:
                break
    
        if hi > lo:
            lut = np.zeros(256, dtype=np.uint8)
            scale_coef = 255.0 / (hi - lo)
            offset = -lo * scale_coef
            for ix in range(256):
                lut[ix] = int(np.clip(ix * scale_coef + offset, 0, 255))
    
            img = cv2.LUT(img, lut)
    
        return img
    
    transform = Lambda(image = lambda img: _autocontrast(img))
    

    P.S. Pull request containing Autocontrast transform is under review for a long time. You may vote for this PR on github in order to highlight it to maintainers :)