Generate 3D Surface Map from Skimage Elevation Map (2D numpy.ndarray) - python

In the skimage Segmentation tutorial, a 3D surface plot of the elevation map generated from the sobel function was plotted.
>>> from skimage.filters import sobel
>>> elevation_map = sobel(coins)
Question: elevation_map appears to be a 2D numpy.ndarray. How do we generate the 3D map shown using this?

This is likely produced using Paraview/VTK;
Try to play around the following:
from skimage import data
from skimage.filters import sobel
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from matplotlib import cm
from scipy.ndimage import zoom
coins = data.coins()
coins = zoom(coins, 10)
elevation_map = sobel(coins)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
m, n=elevation_map.shape
X, Y = np.meshgrid(np.arange(n), np.arange(m))
ax.plot_surface(X, Y, elevation_map, cmap=cm.viridis, antialiased=False)
ax.axis("off")
ax.set_facecolor('black')
plt.show()

Related

Convert cmap values to RGB for PIL.Image

I want to use PIL.Image to save a figure and I want to use matplotlib cmaps to map the data to a color. I have tried the following:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from PIL import Image
M, N = 255, 255
data = np.arange(M*N).reshape((M, N))
cmap_name = 'autumn_r'
cmap_name = cmap_name
cmap = plt.get_cmap(cmap_name)
norm = mpl.colors.Normalize()
scalarMap = cm.ScalarMappable(norm=norm, cmap=cmap)
plt.imshow(data, cmap=cmap)
plt.show()
colors = scalarMap.to_rgba(data)
image = Image.fromarray((colors[:, :, :3]*256).astype(np.uint8))
image.show()
Which plots this in matplotlib:
However, it plots this in the Image:
How can I get PIL.Image to show the same colors as matplotlib?
If its possible to also add the alpha channel, that will be useful
You need to give PIL the same normalisation and cmap you give matplotlib, so it can do the same mapping from 2D array -> normalised -> mapped to cmap.
I rewrote your sample code to be a bit simpler:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from PIL import Image
M, N = 255, 255
data = np.arange(M*N).reshape((M, N))
cmap = cm.autumn_r
plt.imshow(data, cmap=cmap)
norm = mpl.colors.Normalize()
Then your answer is:
Image.fromarray(np.uint8(cmap(norm(data))*255)).show()
(Found the solution here, might be a dupe.)

How to plot multiple parametric plots in a single figure?

I need to plot a family of parametric curves in a single figure for each alpha values as mentioned in the code
import numpy as np
from sympy import *
from sympy.plotting import plot_parametric
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
a=45
t = symbols('t')
for alpha in np.arange(0.5,3,.1):
M=a*sqrt(cos(2*t)+sqrt(pow(alpha,4)+pow(sin(2*t),2)))
x = M*cos(t)
y = M*sin(t)
plot_parametric(x, y, (t, 0, 2*pi))
The code returns a sequence of 2D plots for each alpha value. Instead, I want to plot the whole set of plots in one figure, something like this image attached
Any solution?
from numpy import arange, cos, linspace, pi, sin, sqrt
from matplotlib.pyplot import colorbar, Normalize, show, subplots
from matplotlib.cm import ScalarMappable, viridis
a=45
t= linspace(0, 2*pi, 2001)
norm = Normalize(vmin=0.5, vmax=3)
cmap = viridis
sm = ScalarMappable(cmap=cmap, norm=norm)
fig, (ax_xy, ax_tM) = subplots(1, 2, figsize=(10, 4), constrained_layout=1)
for alpha in arange(0.5,3,.1):
color = cmap(norm(alpha))
M=a*sqrt(cos(2*t)+sqrt(pow(alpha,4)+pow(sin(2*t),2)))
x = M*cos(t)
y = M*sin(t)
ax_tM.plot(t, M, color=color)
ax_xy.plot(x, y, color=color)
colorbar(sm, aspect=40)
show()

how to plot a 2d image in 3d plot for calculating depth of object as z axis?

I want to plot a 2D image in 3D map for calculating depth of object and for same I have made a code but that code is giving me an error for calculating distance z as depth.
error is shape mismatch: objects cannot be broadcast to a single shape
import cv2
import numpy as np
import math
import scipy.ndimage as ndimage
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
image2=cv2.imread('i1.jpg')
image2 = image2[:,:,1] # get the first channel
rows, cols = image2.shape
x, y= np.meshgrid(range(cols), range(rows)[::-1])
blurred = ndimage.gaussian_filter(image2,(5, 5))
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(221)
ax.imshow(image2, cmap='gray')
ax = fig.add_subplot(222, projection='3d')
ax.elev= 5
ax.plot_surface(x,y,z,image2)
ax = fig.add_subplot(223)
ax.imshow(blurred, cmap='gray')
ax = fig.add_subplot(224, projection='3d')
ax.elev= 5
ax.plot_surface(x,y,z,blurred)
plt.show()

Fitting 3D data to a line in python

I want to fit a 3D plot to a line in python. A minimal example is the following:
from pylab import *
import numpy as np
import matplotlib.image as img
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.01)
y = np.arange(-1,1,0.01)
[X,Y] = np.meshgrid(x,y)
z = exp(-(X-8*Y+2)**2/10)
fig,ax = plt.subplots()
im = img.NonUniformImage(ax, interpolation='bilinear')
im.set_data(x,y,z)
ax.images.append(im)
ax.set_xlim(-10,10)
ax.set_ylim(-1,1)
fig.colorbar(im, ax=ax)
plt.show()
The figure generated is:
I want to use a line to fit such data, with a weight such that the dark red data has most weight while the dark blue data has least weight. Essentially, I want to find that the curve is x-8y+2=0.
How do I do this? Thanks!

How to plot a 3D histogram of RGB image in python

I want to plot a 3D histogram of my RGB image.
Below is my code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import imread
import pylab
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
img1 = imread('image.jpg')
img_reshaped = img1.reshape(img1.shape[0] * img1.shape[1], img1.shape[2])
hist, edges = np.histogramdd(img_reshaped, bins=(100, 100, 100))
Please tell me how to plot the hist histogram that I have obtained.
Have you taken a look at the 3d histogram example from the matplotlib gallery?
see: http://matplotlib.org/examples/mplot3d/hist3d_demo.html

Categories