Amazing-Python-Scripts

Форк
0
/
Image Contrast Adjusting Filter.py 
71 строка · 1.7 Кб
1
import numpy as np
2
import matplotlib.pyplot as plt
3
from PIL import Image
4
import os.path
5

6
# example -> C:\Users\xyz\OneDrive\Desktop\project\image.jpg
7
img_path = input("Enter the path here: ")
8
img = Image.open(img_path)
9

10
# convert our image into a numpy array
11
img = np.asarray(img)
12
# print(img.shape)
13
# put pixels in a 1D array by flattening out img array
14
flat = img.flatten()
15

16
# create our own histogram function
17

18

19
def get_histogram(image, bins):
20
    # array with size of bins, set to zeros
21
    histogram = np.zeros(bins)
22

23
    # loop through pixels and sum up counts of pixels
24
    for pixel in image:
25
        histogram[pixel] += 1
26

27
    # return our final result
28
    return histogram
29

30

31
# execute our histogram function
32
hist = get_histogram(flat, 256)
33

34
# execute the fn
35
cs = np.cumsum(hist)
36

37
# numerator & denomenator
38
nj = (cs - cs.min()) * 255
39
N = cs.max() - cs.min()
40

41
# re-normalize the cumsum
42
cs = nj / N
43

44
# cast it back to uint8 since we can't use floating point values in images
45
cs = cs.astype('uint8')
46

47
# get the value from cumulative sum for every index in flat, and set that as img_new
48
img_new = cs[flat]
49

50
# put array back into original shape since we flattened it
51
img_new = np.reshape(img_new, img.shape)
52

53
# set up side-by-side image display
54
fig = plt.figure()
55
fig.set_figheight(15)
56
fig.set_figwidth(15)
57

58
# display the real image
59
fig.add_subplot(1, 2, 1)
60
plt.imshow(img, cmap='gray')
61
plt.title("Image 'Before' Contrast Adjustment")
62

63
# display the new image
64
fig.add_subplot(1, 2, 2)
65
plt.imshow(img_new, cmap='gray')
66
plt.title("Image 'After' Contrast Adjustment")
67
filename = os.path.basename(img_path)
68

69
plt.savefig("./Image Contrast Adjusting Filter/(Contrast Adjusted)"+filename)
70

71
plt.show()
72

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.