How to export Voronoi cell into mask? - python

I am using scipy.spatial to calculate the voronoi cell in my image and to stack the result on my image by using:
from scipy.spatial import Voronoi, voronoi_plot_2d
import numpy as np
import cv2
import matplotlib.pyplot as plt
im = cv2.imread('img.tif', 0)
pks = np.loadtxt('pks.csv', delimiter=',', skiprows = 1)
vor = Voronoi(pks)
plt.figure()
plt.imshow(im, cmap='gray')
ax = plt.gca()
voronoi_plot_2d(vor, show_vertices=False, line_colors='y',
line_width=2, line_alpha=0.6, point_size=2, ax=ax)
plt.axis('off')
plt.show()
How to extract each cell into masks as shown below?

Related

Align image with Sinusoidal projection correctly using imshow and cartopy

I'm trying to plot an image with a Sinusoidal projection using imshow but if I use the transform=ccrs.Sinusoidal(central_longitude=128) it's not working at all and using the transform=ccrs.PlateCarree() the coastlines and image are not aligned. This is my code:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import numpy as np
plt.figure(figsize=(8, 8))
ax = plt.axes(projection=ccrs.PlateCarree())
img_extent = (122.8109, 133.2922, 32.8286, 43.1708)
img = plt.imread('Korea.A2004004.0445.250m.jpg')
ax.coastlines(resolution='10m')
ax.imshow(img, origin='upper', extent=img_extent, transform=ccrs.PlateCarree())
plt.show()
Image is from: https://eoimages.gsfc.nasa.gov/images/imagerecords/69000/69679/Korea.A2004004.0445.250m.jpg

Labeling elements on heatmap using Python [duplicate]

I am trying to highlight minimum values of each row using the same color:
For instance, the first row minimum is 0.3. I want to highlight it with blue color. Similarly, for the second row, 0.042 and so on.
Here's the code.
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
from matplotlib.patches import Rectangle
Pe = np.random.rand(5,5)
annot=True
fig, ax1 = plt.subplots(1)
ax1 = sns.heatmap(Pe, linewidth=0.5,ax=ax1,annot=annot)
You could loop through the rows, find the index of the minimum, and draw a rectangle there. Setting clip_on=False prevents that the rectangles would be clipped by the border.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
Pe = np.random.rand(5, 5)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 4))
sns.set_style('white')
sns.heatmap(Pe, linewidth=0.5, annot=True, ax=ax1)
for ind, row in enumerate(Pe):
min_col = np.argmin(row)
ax1.add_patch(plt.Rectangle((min_col, ind), 1, 1, fc='none', ec='skyblue', lw=5, clip_on=False))
sns.heatmap(Pe, mask=Pe != Pe.min(axis=1, keepdims=True), annot=True, lw=2, linecolor='black', clip_on=False,
cmap=ListedColormap(['skyblue']), cbar=False, ax=ax2)
plt.tight_layout()
plt.show()
PS: To create animations, the Celluloid library is a lightweight option:
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import numpy as np
from celluloid import Camera
Pe = np.random.rand(5, 5)
fig, ax1 = plt.subplots()
camera = Camera(fig)
sns.set_style('white')
row_array = np.arange(Pe.shape[0]).reshape(-1, 1)
for row in range(Pe.shape[0]):
sns.heatmap(Pe, mask=(Pe != Pe.min(axis=1, keepdims=True)) | (row < row_array),
annot=True, lw=2, linecolor='black', clip_on=False,
cmap=ListedColormap(['skyblue']), cbar=False, ax=ax1)
camera.snap()
animation = camera.animate(interval=800)
animation.save('animation.gif')
plt.show()
For more complicated animations, matplotlib's animation API can be considered.

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()

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

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()

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