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()
Related
Original(2018.11.01)
I have 3 numpy:x、y、z,created by my laser scanner(40 degree / 1 step).
I want to used them to build a 3D model.
I think it must should be use matplotlib.tri
But I have no idea to decide triangulated data
Here is my data :https://www.dropbox.com/s/d9p62kv9jcq9bwh/xyz.zip?dl=0
And Original model:https://i.imgur.com/XSyONff.jpg
Code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.tri as mtri
x_all=np.load("x.npy")
y_all=np.load("y.npy")
z_all=np.load("z.npy")
tri = #I have no idea...
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x_all,y_all,z_all,triangles=tri.triangles)
Thank so much.
Update(2018.11.02)
I try this way to decide triangulated data
Delaunay Triangulation of points from 2D surface in 3D with python?
code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.tri as mtri
from stl import mesh
x_all=np.load("x.npy")
y_all=np.load("y.npy")
z_all=np.load("z.npy")
model=np.vstack((x_all,y_all,z_all))
model=np.transpose(model)
model -= model.mean(axis=0)
rad = np.linalg.norm(model, axis=1)
zen = np.arccos(model[:,-1] / rad)
azi = np.arctan2(model[:,1], model[:,0])
tris = mtri.Triangulation(zen, azi)
plt.show()
And my model looks like:
https://i.stack.imgur.com/KVPHP.png
https://i.stack.imgur.com/LLQsQ.png
https://i.stack.imgur.com/HdzFm.png
Even though it has better surface on it,but there is a big hole over my model.Any idea to fixs it?
Assuming you want to reduce the complexity, i.e find triangles in your files to reduce the complexity. You may look into fitting a convex hull to your points, see here fore more info
Based on the file you provided this produces a surf plot of the object.
from numpy import load, stack
from matplotlib.pyplot import subplots
from mpl_toolkits.mplot3d import Axes3D
from scipy import spatial
x = load("x.npy")
y = load("y.npy")
z = load("z.npy")
points = stack((x,y,z), axis = -1)
v = spatial.ConvexHull(points)
fig, ax = subplots(subplot_kw = dict(projection = '3d'))
ax.plot_trisurf(*v.points.T, triangles = v.simplices.T)
fig.show()
I am trying to format the matrix better. My current code gives me o/p in the format as seen in the image:
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(10,10))
plt.matshow(final.corr(), fignum = 1)
plt.xticks(range(len(final.columns)), final.columns)
plt.yticks(range(len(final.columns)), final.columns)
enter code here
import numpy as np
import math
import matplotlib.pylab as plt
a=np.linspace(3,6,10)
plt.plot(a,math.sin(a))
plt.show()
The output says ****TypeError: only size-1 arrays can be converted to Python scalars
Use np.sin or np.vectorize(math.sin).
import numpy as np
import math
import matplotlib.pylab as plt
a = np.linspace(3,6,10)
plt.plot(a, np.sin(a))
plt.show()
Note that np.sin, like math.sin, takes radians rather than degrees, so you may want to adjust your array (a) accordingly, or use np.rad2deg because at the moment the result is:
Whereas if you were to pass in floats between 0 and 2 * math.pi, you would get a nice sine wave:
Consider the following code:
import numpy as np
rand_matrix = np.random.rand(10,10)
which generates a 10x10 random matrix.
Following code to display as colour map:
import matplotlib.pyplot as plt
plt.imshow(rand_matrix)
plt.show()
I would like to get the RGB numpy array (no axis) from the object obtained from plt.imshow
In other words, if I save the image generated from plt.show, I would like to get the 3D RGB numpy array obtained from:
import matplotlib.image as mpimg
img=mpimg.imread('rand_matrix.png')
But without the need to save and load the image, which is computationally very expensive.
Thank you.
You can save time by saving to a io.BytesIO instead of to a file:
import io
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image
def ax_to_array(ax, **kwargs):
fig = ax.figure
frameon = ax.get_frame_on()
ax.set_frame_on(False)
with io.BytesIO() as memf:
extent = ax.get_window_extent()
extent = extent.transformed(fig.dpi_scale_trans.inverted())
plt.axis('off')
fig.savefig(memf, format='PNG', bbox_inches=extent, **kwargs)
memf.seek(0)
arr = mpimg.imread(memf)[::-1,...]
ax.set_frame_on(frameon)
return arr.copy()
rand_matrix = np.random.rand(10,10)
fig, ax = plt.subplots()
ax.imshow(rand_matrix)
result = ax_to_array(ax)
# view using matplotlib
plt.show()
# view using PIL
result = (result * 255).astype('uint8')
img = Image.fromarray(result)
img.show()
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!