In [1]:
# convert image to it's negative - s = L - 1 - r
# where L is max colour resolution
# inline plot magic
%matplotlib inline
In [2]:
# first we import image library
from matplotlib import image
# then plot library
from matplotlib import pyplot
# then numpy
import numpy as np
In [3]:
# read image
img = image.imread('MP.tif')
In [4]:
# lets see how the array looks
img
Out[4]:
In [5]:
# ok, we have data in R cell, lets view it
pyplot.imshow(img)
Out[5]:
In [6]:
# lets find the maximum value
np.max(img)
Out[6]:
In [7]:
# and minimum
np.min(img)
Out[7]:
In [8]:
# sweet, we have 0-255, a 8 bit image
# lets invert it with
def _invert(cell):
return 255-cell
# type of out array need to be uint8 or float32
invert = np.vectorize(_invert, otypes=[np.uint8])
inv_img = invert(img)
In [9]:
# did it work?
inv_img
Out[9]:
In [10]:
# seems like it, lets view it
pyplot.imshow(inv_img)
Out[10]:
In [11]:
# it did work, but it would be sweeter with greyscale
# instead of only red
# lets look at the dimensions
img.shape
Out[11]:
In [14]:
%%time
# ok, we need to change every 2048x2048 pixel
# 2nd+3rd column should be equal to 1st (GB=R in RGB)
def greyscale(row):
# use numpys max
m = row.max()
return np.array([m,m,m], dtype=np.uint8)
grey_img = np.apply_along_axis(greyscale, 2, img)
In [15]:
pyplot.imshow(grey_img)
Out[15]:
In [14]:
# works, but wow, inefficient!
# lets do it by copying
grey_img = np.copy(img)
# to different syntaxes
grey_img[...,1] = grey_img[...,0]
grey_img[:,:,2] = grey_img[:,:,0]
In [15]:
grey_img
Out[15]:
In [16]:
# plot it
pyplot.imshow(grey_img)
Out[16]:
In [17]:
# now invert and show
inv_img = invert(grey_img)
pyplot.imshow(inv_img)
Out[17]:
In [18]:
# single channel psuedo color
pyplot.imshow(img[...,0])
pyplot.colorbar()
Out[18]:
In [19]:
# same with custom colormap, see colormaps.png for available cmaps
pyplot.imshow(img[...,0], cmap='gray')
pyplot.colorbar()
Out[19]:
In [20]:
# all of the above, in oneliner - this is the WINNER :-)
pyplot.imshow(255-img[...,0], cmap='gray')
Out[20]: