I want to use the colormap "viridis" (http://bids.github.io/colormap/), and I won't be updating to the development version 1.5 quite yet. Thus, I have downloaded colormaps.py from https://github.com/BIDS/colormap. Unfortunately, I'm not able to make it work. This is what I do:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import colormaps as cmaps
img=mpimg.imread('stinkbug.png')
lum_img = np.flipud(img[:,:,0])
plt.set_cmap(cmaps.viridis)
imgplot = plt.pcolormesh(lum_img)
This gives me a ValueError, the traceback ending with,
ValueError: Colormap viridis is not recognized. Possible values are: Spectral, summer, coolwarm, ...
(And then the complete list of originally installed colormaps.)
Any thoughts on how to fix this issue?
To set viridis as your colormap using set_cmap, you must register it first:
import colormaps as cmaps
plt.register_cmap(name='viridis', cmap=cmaps.viridis)
plt.set_cmap(cmaps.viridis)
img=mpimg.imread('stinkbug.png')
lum_img = np.flipud(img[:,:,0])
imgplot = plt.pcolormesh(lum_img)
Rather than using set_cmap, which requires a matplotlib.colors.Colormap instance, you can set the cmap directly in the pcolormesh call
(cmaps.viridis is a matplotlib.colors.ListedColormap)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import colormaps as cmaps
img=mpimg.imread('stinkbug.png')
lum_img = np.flipud(img[:,:,0])
imgplot = plt.pcolormesh(lum_img, cmap=cmaps.viridis)
What I did is to just copy the
_viridis_data = [[0.267004, 0.004874, 0.329415],
[0.268510, 0.009605, 0.335427],
[0.269944, 0.014625, 0.341379],
:
[0.983868, 0.904867, 0.136897],
[0.993248, 0.906157, 0.143936]]
from https://github.com/BIDS/colormap/blob/master/colormaps.py
and add:
from matplotlib.colors import ListedColormap
viridis = ListedColormap(_viridis_data, name='viridis')
plt.register_cmap(name='viridis', cmap=viridis)
plt.set_cmap(viridis)
Download the colormaps.py from here,then:
import os,sys
scriptpath = "/Your downloading path/colormap-master/"
sys.path.append(os.path.abspath(scriptpath))
import colormaps as cmaps
Done!
Related
I have a piece of python code that is intended to extract letters and label each region that contains an image.
I'm using google colab
I get the following error:
NameError Traceback (most recent call last)
in ()
1
----> 2 image = imageio.imread('https://pbs.twimg.com/profile_images/985792111713947648/7YD1ZYpe_400x400.jpg')
3
4
5
NameError: name 'imageio' is not defined```
Heres the full code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from scipy.misc import imageio.imread,imresize
from skimage.segmentation import clear_border
from skimage.morphology import label
from skimage.measure import regionprops
image = imageio.imread('https://pbs.twimg.com/profile_images/985792111713947648/7YD1ZYpe_400x400.jpg')
#apply threshold in order to make the image binary
bw = image < 120
# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)
# label image regions
label_image = label(cleared,neighbors=8)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
print(label_image.max())
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(bw, cmap='jet')
You're using a function from a package you haven't imported yet. First you need to install imageio in your system (pip install imageio) and then include it in the code (and removing the other imread). The new code will be:
import imageio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from skimage.segmentation import clear_border
from skimage.morphology import label
If you're going to use imresize you will need to install pillow.
I've been trying to iterate over files in a folder and show them for two seconds each using this code:
import time
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.image import imread
import glob
import cv2
im = []
for filepath in glob.iglob(r'C:\Users\dan20\Pictures\wedding\beeri and adn. photo/*.jpg'):
a = imread(filepath)
b = cv2.resize(a, dsize = (456,304))
im += [b]
fig,ax = plt.subplots()
for i in im:
time.sleep(2)
ax.axis('off')
ax.imshow(i)
plt.show()
For some reason I can't see the images as long as i use time.sleep().
How can I make each picture to appear for N amount of times?
How about using plt.pause :
import numpy as np
from matplotlib import pyplot as plt
im = [np.random.random((9,9)) for i in range(1,6)]
fig,ax = plt.subplots()
for i in im:
ax.cla()
ax.imshow(i)
ax.axis('off')
plt.pause(2)
which gives :
how can I extract contour lines from data imported through cartopy's feature interface? If the solution involves geoviews.feature or another wrapper, that is OK, of course.
For instance, how would I extract the data plotted as cfeature.COASTLINE in the following example?
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
ax = plt.axes(projection=ccrs.PlateCarree())
ax.add_feature(cfeature.COASTLINE)
plt.show()
I'm grateful for any hints you might have!
FWIW, in basemap, I would do it like this:
import mpl_toolkits.basemap as bm
import matplotlib.pyplot as plt
m = bm.Basemap(width=2000e3,height=2000e3,
resolution='l',projection='stere',
lat_ts=70,lat_0=70,lon_0=-60.)
fig,ax=plt.subplots()
coastlines = m.drawcoastlines().get_segments()
You can get the coordinates for the plotted lines directly from the feature, which contains a set of shapely.MultiLineStrings. As a proof of concept, check out this code:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
fig, (ax1,ax2) = plt.subplots(nrows=2, subplot_kw = dict(projection=ccrs.PlateCarree()))
ax1.add_feature(cfeature.COASTLINE)
for geom in cfeature.COASTLINE.geometries():
for g in geom.geoms:
print(list(g.coords))
ax2.plot(*zip(*list(g.coords)))
plt.show()
which gives this picture:
In other words, you can iterate over the MultiLineStrings of the feature by accessing its geometries(). Each of these MultiLineStrings then contains one or more LineStrings, which have a coords attribute that can be converted into a list. Hope this helps.
For future reference: Some time later, I also came across this (more general?) method to access any feature:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
shpfilename = shpreader.natural_earth(resolution='110m',
category='physical',
name='coastline')
coastlines = shpreader.Reader(shpfilename).records()
fig, ax = plt.subplots(subplot_kw = dict(projection=ccrs.PlateCarree()))
for c in coastlines:
for g in c.geometry:
ax.plot(*zip(*list(g.coords)))
yielding the same plot as above.
I wonder if there is a possibility to set the color of a histgram, which is filled in a for loop, at the end of this process like:
import numpy as np
import matplotlib.pylot as plt
x=np.array([[1,1,3,4],[1,4,5,6],[1,4,4,6]])
plt.figure()
for i in range(3):
plt.hist(x[i])
plt.show()
Maybe some comand before the plt.show() ?
You could get hold of the Patch objects which make up the histogram as you go along:
import numpy as np
import matplotlib.pyplot as plt
x=np.array([[1,1,3,4],[1,4,5,6],[1,4,4,6]])
plt.figure()
patches = []
for i in range(3):
_, _, p = plt.hist(x[i])
patches += p
for patch in patches:
patch.set_color('pink')
plt.show()
plt.hist() has the parameter color:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([[1,1,3,4],[1,4,5,6],[1,4,4,6]])
xcolor = ["r", "b", "y"]
plt.hist(x.T, color = xcolor)
plt.show()
This parameter works also in a loop, though the code you provided doesn't produce what you probably expect it to do.
I am attempting to run a DCT transform on an image. I have tried to make my image a grayscale image with the following code:
import numpy as np
import matplotlib.pyplot as plt
import scipy
from numpy import pi
from numpy import sin
from numpy import zeros
from numpy import r_
from scipy import signal
from scipy import misc
import matplotlib.pylab as pylab
#matplotlib inline
pylab.rcParams['figure.figsize'] = (20.0, 7.0)
im = misc.imread("indoorPictureResize.jpg")
#show the image
f = plt.figure()
plt.imshow(im,cmap='gray')
plt.show()
However I receive the image but it's color channel has not changed. Have I done something wrong or is it something I should change?
The array im is probably a 3-D array, with shape (m, n, 3) or (m, n, 4). Check im.shape.
From the imshow docstring: "cmap is ignored if X is 3-D".
To use a colormap, you'll have to pass a 2-D array to imshow. You could, for example, plot one of the color channels such as im[:,:,0], or plot the average over the three channels, im.mean(axis=2). (But if im has shape (m, n, 4), you probably don't want to include the alpha channel in the mean.)
Add the mode in scipy.misc.imread like this:
import numpy as np
import matplotlib.pyplot as plt
import scipy
from numpy import pi
from numpy import sin
from numpy import zeros
from numpy import r_
from scipy import signal
from scipy import misc
import matplotlib.pylab as pylab
#matplotlib inline
pylab.rcParams['figure.figsize'] = (20.0, 7.0)
im = misc.imread("indoorPictureResize.jpg", mode="L")
#show the image
f = plt.figure()
plt.imshow(im,cmap='gray')
plt.show()