Skip to content

Instantly share code, notes, and snippets.

@mpdroid

mpdroid/mona_lisa.py

Last active Dec 1, 2019
Embed
What would you like to do?
Transform Mona Lisa to grayscale using numpy array manipulation
# Based on https://www.degeneratestate.org/posts/2016/Oct/23/image-processing-with-numpy/
import numpy as np
import matplotlib.pylab as plt
import matplotlib.gridspec as gridspec
%matplotlib inline
original = plt.imread("mona_lisa_full.jpg")
original.shape
def plot(image1, image2, h=8, **kwargs):
plt.close('all')
fig = plt.figure(figsize=(16, 16))
gs1 = gridspec.GridSpec(1, 2)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
ax1.axis("off")
ax2.axis("off")
ax1.imshow(image1, interpolation="none", **kwargs)
ax2.imshow(image2, interpolation="none", **kwargs)
gs1.tight_layout(fig)
def to_grayscale(image, weights = np.c_[0.2989, 0.5870, 0.1140]):
"""
Transforms a colour image to a grayscale image by
taking the mean of the RGB values, weighted
by the matrix weights
"""
tile = np.tile(weights, reps=(im.shape[0],im.shape[1],1))
return np.sum(tile * im, axis=2)
grayscale = to_grayscale(original)
plot(original, grayscale, cmap='gray')
@leesmith404

This comment has been minimized.

Copy link

@leesmith404 leesmith404 commented Nov 30, 2019

Thanks for a function image resolution example!
Can you suggest sites or books which further discuss image manipulation with Numpy? I am preparing an Intermediate Python course for fall and I will use numpy, pandas, matplotlib and sympy.
leesmith404@gmail.com

@mpdroid

This comment has been minimized.

Copy link
Owner Author

@mpdroid mpdroid commented Nov 30, 2019

Thanks for your comment.

Obviously google has several suggestions. I found the scipy lectures site to be very useful for a formal tutorial.

The link at the top of the gist https://www.degeneratestate.org/posts/2016/Oct/23/image-processing-with-numpy/ was the best example I could find.

Kaggle has several competitions on image processing and folks have posted their notebooks e.g. https://www.kaggle.com/akshayt19nayak/getting-started-image-processing-basics

@leesmith404

This comment has been minimized.

Copy link

@leesmith404 leesmith404 commented Nov 30, 2019

@mpdroid

This comment has been minimized.

Copy link
Owner Author

@mpdroid mpdroid commented Dec 1, 2019

sorry, no - google is my main tutor. I did buy this once for my kids and found it was useful for grown ups as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment