pythonopencvimage-processingcontrast

How to do a localized Contrast Enhancement In a scanned Image Using OpenCV Python


I was working on a project I wanted to perform a localized contrast enhancement / adaptive contrast enhancement on a couple of images. I have tried thresholding but it is affecting the text of the image. I am attaching the images below

Source: ImageHere

Result: ImageHere

Global contrast and other features are not working. Please do not suggest CLAHE It is giving very weird results. Please help me thank you.


Solution

  • Here is one way to do that in Python/OpenCV using division normalization and some sharpening.


    Input:

    enter image description here

    import cv2
    import numpy as np
    import skimage.filters as filters
    
    # read the image
    img = cv2.imread('math_questions.jpg')
    
    # convert to gray
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    # blur
    smooth = cv2.GaussianBlur(gray, (95,95), 0)
    
    # divide gray by morphology image
    division = cv2.divide(gray, smooth, scale=255)
    
    # sharpen using unsharp masking
    result = filters.unsharp_mask(division, radius=1.5, amount=1.5, multichannel=False, preserve_range=False)
    result = (255*result).clip(0,255).astype(np.uint8)
    
    # save results
    cv2.imwrite('math_question_division.jpg',division)
    cv2.imwrite('math_question_division_sharpen.jpg',result)
    
    # show results
    cv2.imshow('smooth', smooth)  
    cv2.imshow('division', division)  
    cv2.imshow('result', result)  
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    Division image:

    enter image description here

    Sharpened result:

    enter image description here