Giter VIP home page Giter VIP logo

andyhuang1995 / image-contrast-enhancement Goto Github PK

View Code? Open in Web Editor NEW
514.0 5.0 114.0 2.1 MB

Python implementation of "A New Image Contrast Enhancement Algorithm Using Exposure Fusion Framework", CAIP2017

Home Page: https://baidut.github.io/OpenCE/caip2017.html

Python 100.00%
python image-enhancement image-contrast-enhancement low-light-image dynamic-histogram-equalization histogram-equalization

image-contrast-enhancement's Introduction

Image-Contrast-Enhancement

Python implementations of "A New Image Contrast Enhancement Algorithm Using Exposure Fusion Framework"

Already Implemented

  • histogram equalization(he)
  • dynamic histogram equalization(dhe)
  • A New Image Contrast Enhancement Algorithm Using Exposure Fusion Framework

Requirements

  • scipy
  • numpy
  • imageio
  • matplotlib
  • cv2
  • skimage

Usage

If you want the result of "A New Image Contrast Enhancement Algorithm Using Exposure Fusion Framework"

python ying.py <input image>

If you want the result of "A Dynamic Histogram Equalization for Image Contrast Enhancement"

python dhe.py <input image>

If you want the result of histogram equalization

python he.py <input image>

Results

image-contrast-enhancement's People

Contributors

andyhuang1995 avatar jianhao-huang avatar pss1998 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

image-contrast-enhancement's Issues

Warnings from ying.py

When running ying.py I get the following warnings:
RuntimeWarning: invalid value encountered in power
I = (I[:,:,0]*I[:,:,1]*I[:,:,2])**(1/3)
RuntimeWarning: invalid value encountered in greater
tmp[tmp > 255] = 255
RuntimeWarning: invalid value encountered in less
tmp[tmp<0] = 0

Doesn't seem to stop code from executing but i wonder what those warnings mean.

AttributeError: module 'scipy.misc' has no attribute 'imresize'

I tried to use ying.py but I receive an error.

AttributeError: module 'scipy.misc' has no attribute 'imresize'

It's about imresize, because

imresize is deprecated! imresize is deprecated in SciPy 1.0.0, and will be removed in 1.3.0. Use Pillow instead: numpy.array(Image.fromarray(arr).resize()).

About speed

Thanks for your python implement and amazing result, but its slow speed is a problem, do you consider re-implement by Pytorch to accelerate using GPU?

How to enhance contrast for this image

For images like this one (images with text of low contrast), what parameters should I change for a better result?

contrast

I tried the default values with dhe.py and ying.py, it did help enhance the contrast a little bit but not much. I'm wondering whether the author knows better about how to tune some parameters in the program to get a better result for images like the one I provided.

Thank you very much for the code and for your help!

License

Hello, thank you for releasing your work on GitHub.
Could you provide license for this project?

Export Image as PNG instead of just showing on Plot

Hi, I was wondering if you would want to be able to export the image as a PNG instead of just showing it in the plt.show. All you need to do is put something like scipy.misc.imsave('outfile.png', result) as the line right before plt.imshow(result) since [for me at least] when I view it on the plot viewer and try to export I get a tiny file.

DHE Error

I encounter with that error trying to run dhe.py

/home/atasoy/.local/lib/python3.6/site-packages/numpy/lib/function_base.py:2534: RuntimeWarning: invalid value encountered in true_divide
c /= stddev[:, None]
/home/atasoy/.local/lib/python3.6/site-packages/numpy/lib/function_base.py:2535: RuntimeWarning: invalid value encountered in true_divide
c /= stddev[None, :]

File "<ipython-input-18-8ca944b6a0f0>", line 120 isBad = t_our < 0.5 ^ SyntaxError: invalid syntax

import numpy as np
import matplotlib.pyplot as plt
import imageio
import scipy, scipy.misc, scipy.signal
import cv2
import sys

def computeTextureWeights(fin, sigma, sharpness):
dt0_v = np.vstack((np.diff(fin, n=1, axis=0), fin[0,:]-fin[-1,:]))
dt0_h = np.vstack((np.diff(fin, n=1, axis=1).conj().T, fin[:,0].conj().T-fin[:,-1].conj().T)).conj().T

gauker_h = scipy.signal.convolve2d(dt0_h, np.ones((1,sigma)), mode='same')
gauker_v = scipy.signal.convolve2d(dt0_v, np.ones((sigma,1)), mode='same')

W_h = 1/(np.abs(gauker_h)*np.abs(dt0_h)+sharpness)
W_v = 1/(np.abs(gauker_v)*np.abs(dt0_v)+sharpness)

return  W_h, W_v

def solveLinearEquation(IN, wx, wy, lamda):
[r, c] = IN.shape
k = r * c
dx = -lamda * wx.flatten('F')
dy = -lamda * wy.flatten('F')
tempx = np.roll(wx, 1, axis=1)
tempy = np.roll(wy, 1, axis=0)
dxa = -lamda *tempx.flatten('F')
dya = -lamda *tempy.flatten('F')
tmp = wx[:,-1]
tempx = np.concatenate((tmp[:,None], np.zeros((r,c-1))), axis=1)
tmp = wy[-1,:]
tempy = np.concatenate((tmp[None,:], np.zeros((r-1,c))), axis=0)
dxd1 = -lamda * tempx.flatten('F')
dyd1 = -lamda * tempy.flatten('F')

wx[:,-1] = 0
wy[-1,:] = 0
dxd2 = -lamda * wx.flatten('F')
dyd2 = -lamda * wy.flatten('F')

Ax = scipy.sparse.spdiags(np.concatenate((dxd1[:,None], dxd2[:,None]), axis=1).T, np.array([-k+r,-r]), k, k)
Ay = scipy.sparse.spdiags(np.concatenate((dyd1[None,:], dyd2[None,:]), axis=0), np.array([-r+1,-1]), k, k)
D = 1 - ( dx + dy + dxa + dya)
A = ((Ax+Ay) + (Ax+Ay).conj().T + scipy.sparse.spdiags(D, 0, k, k)).T

tin = IN[:,:]
tout = scipy.sparse.linalg.spsolve(A, tin.flatten('F'))
OUT = np.reshape(tout, (r, c), order='F')

return OUT

def tsmooth(img, lamda=0.01, sigma=3.0, sharpness=0.001):
I = cv2.normalize(img.astype('float64'), None, 0.0, 1.0, cv2.NORM_MINMAX)
x = np.copy(I)
wx, wy = computeTextureWeights(x, sigma, sharpness)
S = solveLinearEquation(I, wx, wy, lamda)
return S

def rgb2gm(I):
if (I.shape[2] == 3):
I = cv2.normalize(I.astype('float64'), None, 0.0, 1.0, cv2.NORM_MINMAX)
I = np.abs((I[:,:,0]*I[:,:,1]*I[:,:,2]))**(1/3)

return I

def applyK(I, k, a=-0.3293, b=1.1258):
f = lambda x: np.exp((1-xa)*b)
beta = f(k)
gamma = k
a
J = (I**gamma)*beta
return J

def entropy(X):
tmp = X * 255
tmp[tmp > 255] = 255
tmp[tmp<0] = 0
tmp = tmp.astype(np.uint8)
_, counts = np.unique(tmp, return_counts=True)
pk = np.asarray(counts)
pk = 1.0*pk / np.sum(pk, axis=0)
S = -np.sum(pk * np.log2(pk), axis=0)
return S

def maxEntropyEnhance(I, isBad, a=-0.3293, b=1.1258):
# Esatimate k
tmp = cv2.resize(I, (50,50), interpolation=cv2.INTER_AREA)
tmp[tmp<0] = 0
tmp = tmp.real
Y = rgb2gm(tmp)

isBad = isBad * 1
isBad = scipy.misc.imresize(isBad, (50,50), interp='bicubic', mode='F')
isBad[isBad<0.5] = 0
isBad[isBad>=0.5] = 1
Y = Y[isBad==1]

if Y.size == 0:
   J = I
   return J

f = lambda k: -entropy(applyK(Y, k))
opt_k = scipy.optimize.fminbound(f, 1, 7)

# Apply k
J = applyK(I, opt_k, a, b) - 0.01
return J

def Ying_2017_CAIP(img, mu=0.5, a=-0.3293, b=1.1258):
lamda = 0.5
sigma = 5
I = cv2.normalize(img.astype('float64'), None, 0.0, 1.0, cv2.NORM_MINMAX)

# Weight matrix estimation
t_b = np.max(I, axis=2)
t_our = cv2.resize(tsmooth(np.array(Image.fromarray(t_b, mode="F").resize((int(0.5 * t_b.shape[0]), int(t_b.shape[1] * 0.5)),resample=PIL.Image.BICUBIC), lamda, sigma), (t_b.shape[1], t_b.shape[0]), interpolation=cv2.INTER_AREA)
 
# Apply camera model with k(exposure ratio)
isBad = t_our < 0.5
J = maxEntropyEnhance(I, isBad)

# W: Weight Matrix
t = np.zeros((t_our.shape[0], t_our.shape[1], I.shape[2]))
for i in range(I.shape[2]):
    t[:,:,i] = t_our
W = t**mu

I2 = I*W
J2 = J*(1-W)

result = I2 + J2
result = result * 255
result[result > 255] = 255
result[result<0] = 0
return result.astype(np.uint8)

def main():
img_name = sys.argv[1]
img = imageio.imread('02.jpg')
result = Ying_2017_CAIP(img)
plt.imshow(result)
plt.show()

if name == 'main':
main()

its not working,first there was some problem with weight matrix estimation because of some module were removed from it,so I find another way ,but its still not working

KeyError: "None of [Index(['file_path'], dtype='object')] are in the [columns]

I tried to run the file Ying.py and it's giving me the following error while trying to call the function. I couldn't understand what is causing this error. I want to do some image enhancement so that my model can better understand them while training. This is how I called the function to perform image enhancement on multiple images. log is a simple print function defined by me to print data with the date-time appended to a file.


def imgOptim():
    print('started')
    root_dir = 'Contrast_Corrected'
    log("####################### image Optimization started ######################")
    #data_csv = pd.read_csv("DataSet_Final.csv")

    #create directory structure for saving cropped images
    os.mkdir(root_dir)
    classes_dir = ['Andy_Serkis', 'Angelina_Jolie', 'David_Schwimmer', 'Jennifer_Aniston', 'Lou_Ferrigno']

    ################Processing Started for Cropping face images######################
    log("Image Correction Script started at :: ")
    processed_dir = 'Cropped Images'
    for cls in classes_dir:
        src = processed_dir + "\\" + cls  # Folder to copy images from

        allFileNames = os.listdir(src)
        os.makedirs(root_dir + '\\' + cls)
        print(allFileNames)

        # Copy-pasting images
        for name in allFileNames:
            img_path = src + '\\' + name
            print(img_path)
            image = imageio.imread(img_path)
            print(image)
            result = Ying_2017_CAIP(image)
            contrast = result.astype('float32')
            #optim.save(os.path.join(root_dir+'\\'+cls, name))
            cv2.imwrite(os.path.join(root_dir+'\\'+cls, name), cv2.cvtColor(contrast, cv2.COLOR_RGB2BGR))

    log("Script Ended at :: ")

Error I faced:

Traceback (most recent call last):
File "C:/DIP_Ankita/image_corrector.py", line 12, in
data = data[['file_path']]
File "C:\Users\srchirag27\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\frame.py", line 3001, in getitem
indexer = self.loc._convert_to_indexer(key, axis=1, raise_missing=True)
File "C:\Users\srchirag27\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1285, in _convert_to_indexer
return self._get_listlike_indexer(obj, axis, **kwargs)[1]
File "C:\Users\srchirag27\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1092, in _get_listlike_indexer
keyarr, indexer, o._get_axis_number(axis), raise_missing=raise_missing
File "C:\Users\srchirag27\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1177, in _validate_read_indexer
key=key, axis=self.obj._get_axis_name(axis)
KeyError: "None of [Index(['file_path'], dtype='object')] are in the [columns]"

batch run in pycharm(not terminal)

only change the def main,code as follow:

def main():
test_path = 'testdata'
save_path = 'result'
imgs = os.listdir(test_path)
time_sum = 0
for file in imgs:
# img_name = sys.argv[1]
img_name = os.path.join(test_path,file)
img = imageio.imread(img_name)
ta = time.time()
result = Ying_2017_CAIP(img) # result: ndarray (m,n,4)
time_sum += (time.time()-ta)

    # plt.imshow(result)
    # plt.show()
    save_image = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
    cv2.imwrite('result/{}'.format(file), save_image)
print('time_mean:', (time_sum/len(imgs)*1000))

if name == 'main':
main()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.