Visualization with Matplotlib -2 2D arrays, Images

2D arrays

Images

In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import IPython.display as dp

pixel intensity

  • small is black
  • large is white
In [2]:
u=np.linspace(-2,2,3)
v=np.linspace(-1,1,5)
X,Y=np.meshgrid(u,v)
In [3]:
X
Out[3]:
array([[-2.,  0.,  2.],
       [-2.,  0.,  2.],
       [-2.,  0.,  2.],
       [-2.,  0.,  2.],
       [-2.,  0.,  2.]])
In [4]:
Y
Out[4]:
array([[-1. , -1. , -1. ],
       [-0.5, -0.5, -0.5],
       [ 0. ,  0. ,  0. ],
       [ 0.5,  0.5,  0.5],
       [ 1. ,  1. ,  1. ]])
In [5]:
dp.Image('1.jpg',width=400,height=400)
Out[5]:
In [6]:
Z = X**2/25 + Y**2/4
Z
Out[6]:
array([[ 0.41  ,  0.25  ,  0.41  ],
       [ 0.2225,  0.0625,  0.2225],
       [ 0.16  ,  0.    ,  0.16  ],
       [ 0.2225,  0.0625,  0.2225],
       [ 0.41  ,  0.25  ,  0.41  ]])
In [7]:
plt.figure(figsize=(5,2))
plt.set_cmap('gray')
plt.pcolor(Z)
plt.xlabel('X')
plt.ylabel('Y')
Out[7]:
<matplotlib.text.Text at 0x7f15373a3f50>

writing special characters in matplotlib

http://matplotlib.org/users/mathtext.html

In [8]:
a,b=np.meshgrid(np.linspace(-3,3),np.linspace(-2,2))
z=a**2/25 + b**2/4
plt.figure(figsize=(5,2))
plt.set_cmap('gray')
plt.pcolor(z)
plt.text(15,25,r'$f(x,y)=\frac{x^2}{25}+\frac{y^2}{25}$',color='w',fontsize=13)
plt.xlabel('X')
plt.ylabel('Y')
Out[8]:
<matplotlib.text.Text at 0x7f15348f13d0>
In [9]:
plt.figure(figsize=(5,2))
plt.pcolor(np.array([[1,2,3,2,1,0],[4,5,6,7,8,9]]))
Out[9]:
<matplotlib.collections.PolyCollection at 0x7f153450f2d0>
In [10]:
dp.Image('2.jpg',width=400,height=400)
Out[10]:

Generating meshes

  • In order to visualize two-dimensional arrays of data, it is necessary to understand how to generate and manipulate 2-D arrays.
  • visualise using plt.imshow()

colormaps http://matplotlib.org/examples/color/colormaps_reference.html

  • colorbar
In [11]:
plt.figure(figsize=(5,3))

# Generate two 1-D arrays: u, v
u = np.linspace(-2, 2, 41)
v = np.linspace(-1, 1, 21)

# Generate 2-D arrays from u and v: X, Y
X,Y = np.meshgrid(u, v)

# Compute Z based on X and Y
Z = np.sin(3*np.sqrt(X**2 + Y**2)) 

# Display the resulting image with pcolor()
plt.pcolor(Z, cmap='Blues')
plt.colorbar()
plt.axis('tight')

# Save the figure to 'sine_mesh.png'
plt.savefig('sine_mesh.jpg')


plt.show()

pcolor(x,y,z)

In [12]:
plt.figure(figsize=(5,3))
plt.pcolor(X,Y,Z,cmap='Reds')
Out[12]:
<matplotlib.collections.PolyCollection at 0x7f15342a6310>

contour

In [13]:
plt.contour(Z,12,cmap='brg')
Out[13]:
<matplotlib.contour.QuadContourSet at 0x7f1534134b50>

contourf

In [14]:
plt.contourf(Z,12,cmap='Blues')
Out[14]:
<matplotlib.contour.QuadContourSet at 0x7f15340dca10>

Improve the spacing between the subplots with plt.tight_layout() and display the figure.

In [15]:
plt.set_cmap('winter')
# Generate a default contour map of the array Z
plt.subplot(2,2,1)
plt.contour(X, Y, Z)

# Generate a contour map with 20 contours
plt.subplot(2,2,2)
plt.contour(X, Y, Z, 20)

# Generate a default filled contour map of the array Z
plt.subplot(2,2,3)
plt.contourf(X, Y, Z)

# Generate a contour map with 20 contours
plt.subplot(2,2,4)
plt.contourf(X, Y, Z, 20)

# Improve the spacing between subplots
plt.tight_layout()

# Display the figure
plt.show()

visualize 2-D histograms using plt.hist2d()

  • You specify the coordinates of the points using plt.hist2d(x,y) assuming x and y are two vectors of the same length.
  • You can specify the number of bins with the argument bins=(nx, ny) where nx is the number of bins to use in the horizontal direction and ny is the number of bins to use in the vertical direction.
  • You can specify the rectangular region in which the samples are counted in constructing the 2D histogram. The optional parameter required is range=((xmin, xmax), (ymin, ymax))
    • xmin and xmax are the respective lower and upper limits for the variables on the x-axis and
    • ymin and ymax are the respective lower and upper limits for the variables on the y-axis. Notice that the optional range argument can use nested tuples or lists.
In [16]:
# Generate a 2-D histogram
plt.hist2d(np.random.randint(0,10,1000), 
           np.random.randint(0,30,1000), 
           bins=(20,20), 
           range=((0,13), (0, 35))
          ,cmap='Blues')

# Add a color bar to the histogram
plt.colorbar()

# Add labels, title, and display the plot
plt.xlabel('Horse power [hp]')
plt.ylabel('Miles per gallon [mpg]')
plt.title('hist2d() plot')
plt.show()

generate random integars

In [17]:
np.random.randint(0,20,(5,3))
Out[17]:
array([[10, 12, 19],
       [10,  9,  2],
       [ 9,  1, 12],
       [16,  3, 19],
       [10,  0, 10]])

hexbin(), not very useful

Images

  • loading images using plt.imread()

  • The color image can be plotted as usual using plt.imshow()

  • The resulting image loaded is a NumPy array of three dimensions. The array typically has dimensions M×N×3, where M×N is the dimensions of the image. The third dimensions are referred to as color channels (typically red, green, and blue).
In [18]:
# Load the image into an array: img
img = plt.imread('cat.jpg')

# Print the shape of the image
print(img.shape)

# Display the image
plt.imshow(img)

# Hide the axes
plt.axis('off')
plt.show()
(194, 259, 3)
In [19]:
# Load the image into an array: img
img = plt.imread('cat.jpg')

# Print the shape of the image
print(img.shape)

# Compute the sum of the red, green and blue channels: intensity
intensity = img.sum(axis=2)

# Print the shape of the intensity
print(intensity.shape)

# Display the intensity with a colormap of 'gray'
plt.imshow(intensity, cmap='gray')

# Add a colorbar
plt.colorbar()

# Hide the axes and show the figure
plt.axis('off')
plt.show()
(194, 259, 3)
(194, 259)
In [20]:
img = plt.imread('cat.jpg')
plt.imshow(img[:50])
img[:50].shape
Out[20]:
(50, 259, 3)

Extent and aspect

  • When using plt.imshow() to display an array, the default behavior is to keep pixels square so that the height to width ratio of the output matches the ratio determined by the shape of the array. In addition, by default, the x- and y-axes are labeled by the number of samples in each direction.
  • The ratio of the displayed width to height is known as the image aspect
  • the range used to label the x- and y-axes is known as the image extent.
  • The default aspect value of 'auto' keeps the pixels square and the extents are automatically computed from the shape of the array if not specified otherwise.
In [21]:
# Load the image into an array: img
img = plt.imread('cat.jpg')

# Specify the extent and aspect ratio of the top left subplot
plt.subplot(2,2,1)
plt.title('extent=(-1,1,-1,1),\naspect=0.5')
plt.xticks([-1,0,1])
plt.yticks([-1,0,1])
plt.imshow(img, extent=(-1,1,-1,1), aspect=0.5)

# Specify the extent and aspect ratio of the top right subplot
plt.subplot(2,2,2)
plt.title('extent=(-1,1,-1,1),\naspect=1')
plt.xticks([-1,0,1])
plt.yticks([-1,0,1])
plt.imshow(img, extent=(-1,1,-1,1), aspect=1)

# Specify the extent and aspect ratio of the bottom left subplot
plt.subplot(2,2,3)
plt.title('extent=(-1,1,-1,1),\naspect=2')
plt.xticks([-1,0,1])
plt.yticks([-1,0,1])
plt.imshow(img, extent=(-1,1,-1,1), aspect=2)

# Specify the extent and aspect ratio of the bottom right subplot
plt.subplot(2,2,4)
plt.title('extent=(-2,2,-1,1),\naspect=2')
plt.xticks([-2,-1,0,1,2])
plt.yticks([-1,0,1])
plt.imshow(img, extent=(-2,2,-1,1), aspect=2)

# Improve spacing and display the figure
plt.tight_layout()
plt.show()
In [22]:
img = plt.imread('cat.jpg')
plt.imshow(img[:50], extent=(0,77,0,22),aspect=1)
img[:50].shape
Out[22]:
(50, 259, 3)

Rescaling pixel intensities

  • Sometimes, low contrast images can be improved by rescaling their intensities.
In [23]:
# Load the image into an array: image
image = plt.imread('cat.jpg')

# Extract minimum and maximum values from the image: pmin, pmax
pmin, pmax = image.min(), image.max()
print("The smallest & largest pixel intensities are %d & %d." % (pmin, pmax))

# Rescale the pixels: rescaled_image
rescaled_image = 256*(image - pmin) / (pmax - pmin)
print("The rescaled smallest & largest pixel intensities are %.1f & %.1f." % 
      (rescaled_image.min(), rescaled_image.max()))

# Display the original image in the top subplot
plt.subplot(2,1,1)
plt.title('original image')
plt.axis('off')
plt.imshow(image)

# Display the rescaled image in the bottom subplot
plt.subplot(2,1,2)
plt.title('rescaled image')
plt.axis('off')
plt.imshow(rescaled_image)

plt.show()
The smallest & largest pixel intensities are 0 & 255.
The rescaled smallest & largest pixel intensities are 0.0 & 256.0.
In [ ]:
 
In [ ]:
 

Leave a Reply

Your email address will not be published.

Notice: Undefined index: cookies in /var/www/html/wp-content/plugins/live-composer-page-builder/modules/tp-comments-form/module.php on line 1638