Skip to content

Commit 8bc1f3a

Browse files
committed
contrast enhacement implementation
1 parent b0a8d06 commit 8bc1f3a

File tree

8 files changed

+58
-0
lines changed

8 files changed

+58
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Contrast enhancement image
2+
3+
Using the histogram equalization, we can enhance the contrast in low contrast images. This algorithm uses the cummulative distribution function to map the intensities of a low distribuited histogram into a one more spreaded. Have a look to this [explanation](https://en.wikipedia.org/wiki/Histogram_equalization)
4+
5+
![output example](example.png)
6+
7+
## Requirements
8+
9+
This program only uses the libraries
10+
11+
- Numpy
12+
- Matplotlib
13+
14+
## Running the code
15+
16+
inside of the `Contrast enhancement` folder run:
17+
18+
> `python3 contrast_enhancement.py`
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
4+
def rgb2gray(rgb_img):
5+
"convert an RGB image into single channel grayscale image"
6+
r, g, b = rgb_img[:, :, 0], rgb_img[:, :, 1], rgb_img[:, :, 2]
7+
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
8+
return gray
9+
10+
11+
def histogram_equalization(img):
12+
"""mapping of a low contrast histogram into one with high contrast
13+
using the cummulative distribution function(cdf)"""
14+
img = rgb2gray(img).astype('int')
15+
#transform the image into 1D for better performance
16+
img_1D = img.ravel()
17+
hist, _ = np.histogram(img_1D, 256, density=True)
18+
bins = np.array(range(256))
19+
histNorm = hist/hist.size
20+
cdf = (histNorm.cumsum()*255**2).astype('int')
21+
output = np.zeros(img.size)
22+
#mapping of each pixel into better contrast hist
23+
for i in range(img.size):
24+
output[i] = cdf[img_1D[i]]
25+
output = np.reshape(output, img.shape)
26+
return output
27+
28+
def show_images(img, output):
29+
"""compare the input and output images"""
30+
plt.figure()
31+
plt.subplot(121), plt.imshow(img, cmap='gray'), plt.title('original image'), plt.axis('off')
32+
plt.subplot(122), plt.imshow(output, cmap='gray'), plt.title('contrast enhancement img'), plt.axis('off')
33+
plt.show()
34+
35+
if __name__ == '__main__':
36+
img = plt.imread('images/lumbar_spine.jpg')
37+
output = histogram_equalization(img)
38+
show_images(img, output)
1.07 MB
Loading
191 KB
Loading
79.7 KB
Loading
362 KB
Loading
256 KB
Loading
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
numpy
2+
matplotlib

0 commit comments

Comments
 (0)