|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Created on Fri Sep 28 15:22:29 2018 |
| 4 | +
|
| 5 | +@author: Binish125 |
| 6 | +""" |
| 7 | +import copy |
| 8 | +import os |
| 9 | + |
| 10 | +import numpy as np |
| 11 | + |
| 12 | +import cv2 |
| 13 | +import matplotlib.pyplot as plt |
| 14 | + |
| 15 | + |
| 16 | +class contrastStretch: |
| 17 | + def __init__(self): |
| 18 | + self.img = "" |
| 19 | + self.original_image = "" |
| 20 | + self.last_list = [] |
| 21 | + self.rem = 0 |
| 22 | + self.L = 256 |
| 23 | + self.sk = 0 |
| 24 | + self.k = 0 |
| 25 | + self.number_of_rows = 0 |
| 26 | + self.number_of_cols = 0 |
| 27 | + |
| 28 | + def stretch(self, input_image): |
| 29 | + self.img = cv2.imread(input_image, 0) |
| 30 | + self.original_image = copy.deepcopy(self.img) |
| 31 | + x, _, _ = plt.hist(self.img.ravel(), 256, [0, 256], label="x") |
| 32 | + self.k = np.sum(x) |
| 33 | + for i in range(len(x)): |
| 34 | + prk = x[i] / self.k |
| 35 | + self.sk += prk |
| 36 | + last = (self.L - 1) * self.sk |
| 37 | + if self.rem != 0: |
| 38 | + self.rem = int(last % last) |
| 39 | + last = int(last + 1 if self.rem >= 0.5 else last) |
| 40 | + self.last_list.append(last) |
| 41 | + self.number_of_rows = int(np.ma.count(self.img) / self.img[1].size) |
| 42 | + self.number_of_cols = self.img[1].size |
| 43 | + for i in range(self.number_of_cols): |
| 44 | + for j in range(self.number_of_rows): |
| 45 | + num = self.img[j][i] |
| 46 | + if num != self.last_list[num]: |
| 47 | + self.img[j][i] = self.last_list[num] |
| 48 | + cv2.imwrite("output_data/output.jpg", self.img) |
| 49 | + |
| 50 | + def plotHistogram(self): |
| 51 | + plt.hist(self.img.ravel(), 256, [0, 256]) |
| 52 | + |
| 53 | + def showImage(self): |
| 54 | + cv2.imshow("Output-Image", self.img) |
| 55 | + cv2.imshow("Input-Image", self.original_image) |
| 56 | + cv2.waitKey(5000) |
| 57 | + cv2.destroyAllWindows() |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + file_path = os.path.join(os.path.basename(__file__), "image_data/input.jpg") |
| 62 | + stretcher = contrastStretch() |
| 63 | + stretcher.stretch(file_path) |
| 64 | + stretcher.plotHistogram() |
| 65 | + stretcher.showImage() |
0 commit comments