Created
October 23, 2016 23:53
-
-
Save libbkmz/b64e1563c3ad1377d30d4dd807714b02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
IMG_URL = "/tmp/img_res.jpg" | |
CM = plt.cm.gist_gray | |
def rgb2gray(img): | |
# массив весов для конвертации в grayscale, RGB | |
# W = np.array([0.2126, 0.7152, 0.0722]) | |
W = np.array([0.299, 0.587, 0.114]) | |
# W = np.array([0.333, 0.333, 0.333]) | |
# matrix multiplication: img * W | |
return np.dot(img, W).astype(np.uint8) | |
def calc_gray_hist(img): | |
out = np.zeros(shape=(256, ), dtype=np.uint32) | |
for vl in img.flatten(): | |
out[vl] += 1 | |
return out | |
def gamma_correction(img, c, y): | |
# g = c * img^y | |
return c * np.power(img, y) | |
def put_impulse_noise(img): | |
lim = img.size/16 | |
noise_items_count = int(np.abs(np.random.normal(0, lim))) | |
if noise_items_count > lim: | |
noise_items_count = lim | |
rnd_indeces = np.random.randint(0, img.size, noise_items_count) | |
img_flat = img.copy().reshape(img.size) | |
orig_shape = img.shape | |
img_flat[rnd_indeces] = 255 | |
return img_flat.reshape(orig_shape) | |
def median_filter(img, size): | |
img = img.copy() | |
MEDIAN_FILTER_SIZE = size | |
assert MEDIAN_FILTER_SIZE % 2 == 1 | |
# skip boundariess | |
# @TODO: implement using boundaries | |
skip_size = (MEDIAN_FILTER_SIZE - 1 )/2 | |
for x in xrange(skip_size, img.shape[0]-skip_size): | |
for y in xrange(skip_size, img.shape[1]-skip_size): | |
sub_matrix = img[x-skip_size:x+skip_size+1, y-skip_size:y+skip_size+1] | |
items = np.sort(sub_matrix.flatten()) | |
img[x,y] = items[items.size/2] | |
return img | |
def show_img_with_hist(img): | |
fig = plt.figure() | |
ax1 = fig.add_subplot(121) | |
ax2 = fig.add_subplot(122) | |
img[img > 255] = 255 | |
ax1.imshow(img, cmap=CM, vmin=0, vmax=256) | |
ax2.plot(calc_gray_hist(img)) | |
plt.show() | |
img = plt.imread(IMG_URL) | |
img_gray = rgb2gray(img) # matrix multiplication | |
img_hist = calc_gray_hist(img_gray) | |
img_corr = gamma_correction(img_gray, c=1.0, y=1.0/1.05) | |
show_img_with_hist(img_gray) | |
show_img_with_hist(img_corr) | |
img_noise = put_impulse_noise(img_gray) | |
show_img_with_hist(img_noise) | |
show_img_with_hist(median_filter(img_noise, 11)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment