what distance represent two adjacents pixels - python

I have a 3d point cloud. I used matplotlib to draw a scatterplot representing the point cloud viewed from above. The point cloud is stored as a list of coordinates in meters. The output of matplotlib.pyplot.scatter is a png image.
In addition to saving the image, I want to save the correspondence pixels <-> meters. How to do that?
Here the code I use to make my image with matplotlib. I use a dataframe to manipulate the point cloud.
colors = np.array((self.cloud["red"], self.cloud["green"], self.cloud["blue"])).T
dpi = 72
print("dpi: ",dpi)
fig = plt.figure(figsize=(18000/dpi, 18000/dpi), dpi=dpi)
ax = plt.axes(projection='3d')
ax.view_init(elev=90., azim = 0)
ax.set_snap(True)
ax.scatter(
self.cloud["x"],
self.cloud["y"],
self.cloud["z"],
marker=MarkerStyle('.', fillstyle = 'full'),
facecolors=colors / 255,
zdir="z",
#to set a point to 1 pixel we use the relation (dpi/fig.dpi) but
#the problem of the point cloud is the fact that we didn't have a point at each pixel so we increase the size of a point
#the size is empiric so need to be careful
s = (25)**2,
)
plt.axis('off')
self.set_proper_aspect_ratio(ax)
fig.tight_layout()
plt.savefig(file_name, orientation = 'portrait', transparent = True, dpi=fig.dpi)

To find this distance i use this code:
inv = ax.transData.inverted()
#center_image is in pixel
distance_x = abs(inv.transform((center_image[0],center_image[1]))[0])
distance_y = abs(inv.transform((center_image[0],center_image[1]))[1])

Related

How to evenly spread annotation imageboxes around a scatterplot?

I would like to annotate a scatterplot with images corresponding to each datapoint. With standard parameters the images end up clashing with each other and other important features such as legend axis, etc. Thus, I would like the images to form a circle or a rectangle around the main scatter plot.
My code looks like this for now and I am struggling to modify it to organise the images around the center point of the plot.
import matplotlib.cbook as cbook
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import seaborn as sns
#Generate n points around a 2d circle
def generate_circle_points(n, centre_x, center_y, radius=1):
"""Generate n points around a circle.
Args:
n (int): Number of points to generate.
centre_x (float): x-coordinate of circle centre.
center_y (float): y-coordinate of circle centre.
radius (float): Radius of circle.
Returns:
list: List of points.
"""
points = []
for i in range(n):
angle = 2 * np.pi * i / n
x = centre_x + radius * np.cos(angle)
y = center_y + radius * np.sin(angle)
points.append([x, y])
return points
fig, ax = plt.subplots(1, 1, figsize=(7.5, 7.5))
data = pd.DataFrame(data={'x': np.random.uniform(0.5, 2.5, 20),
'y': np.random.uniform(10000, 50000, 20)})
with cbook.get_sample_data('grace_hopper.jpg') as image_file:
image = plt.imread(image_file)
# Set logarithmic scale for x and y axis
ax.set(xscale="log", yscale='log')
# Add grid
ax.grid(True, which='major', ls="--", c='gray')
coordianates = generate_circle_points(n=len(data),
centre_x=0, center_y=0, radius=10)
# Plot the scatter plot
scatter = sns.scatterplot(data=data, x='x', y='y', ax=ax)
for index, row in data.iterrows():
imagebox = OffsetImage(image, zoom=0.05)
imagebox.image.axes = ax
xy = np.array([row['x'], row['y']])
xybox = np.array(coordianates[index])
ab = AnnotationBbox(imagebox, xy,
xycoords='data',
boxcoords="offset points",
xybox=xybox,
pad=0)
ax.add_artist(ab)
for the moment the output looks like this:enter image description here
Ideally I would like the output to look to something like this:
enter image description here
Many thanks in advance for your help
Not an answer but a long comment:
You can control the location of the arrows, but sometimes it is easier to export figures as SVGs and edit them in Adobe Illustrator or Inkscape.
R has a dodge argument which is really nice, but even then is not always perfect. Solutions in Python exist but are laborious.
The major issue is that this needs to be done last as alternations to the plot would make it problematic. A few points need mentioning.
Your figures will have to have a fixed size (57mm / 121mm / 184mm for Science, 83mm / 171mm for RSC, 83mm / 178mm for ACS etc.), if you need to scale the figure in Illustrator keep note of the scaling factor, adding it as a textbox outside of the canvas —as the underlying plot will need to be replaced at least once due to Murphy's law. Exporting at the right size the SVG is ideal. Sounds silly, but it helps. Likewise, make sure the font size does not go under the minimum spec (7-9 points).

How to modify some axis' attribute with an image in python?

I have an image in python. It's a map of california, and I need to place some point on this map.
The coordonate of each point are retrieve from a csv. But the value of each coordinate are in latitude/longitude. So, i need to convert it to the dimension of my picture.
So, here's is the description of my situation:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# dpi for the saved figure: https://stackoverflow.com/a/34769840/3129414
dpi = 120
img = mpimg.imread("california_map_blank.png")
height, width, bands = img.shape
# Update figure size based on image size
figsize = width / float(dpi), height / float(dpi)
# Create a figure of the right size with one axes that takes up the full figure
figure = plt.figure(figsize=figsize)
axes = figure.add_axes([0, 0, 1, 1])
# Draw the image
axes.imshow(img, interpolation='nearest')
Here's the result:
First i need to modify the y-axis. I need to inverse it so the 0 start at the bottom. Then I need to modify the value of the axis, [31,42] for y-axis and [-123,-114] for x-axis. Because the point I want to place in this map are all in this range. One example of coordinate: 41.76440000093729, -124.1998.
Now here's my question. Is it possible to achieve this ? How ?
PS: I use python 3.6, and I already know how to place point on the image. I don't need to save the image just showing.
PPS: My final goal in fact is to convert lat/lon data into coordinate in a picture so if you know any other way to do it(in Python of course) please tell me.
EDIT: If I apply this: axes.set_xlim(-124.5,-114) it give me this:
I want to have the axis with this range but with the whole image.
In fact, at the end I will not display the axis I will just put the map with the points, but I need to place the point on the map so I think I need to go through this step.
EDIT2: I tried this: axes.imshow(img[::-1], origin='lower', interpolation='nearest') it works fine to reverse the axis but when I draw a point python draw it in the same place when I the axis was normal.
You need to set the limits of the image via the extent= parameter of imshow. These should be quite precise values for the longitudes left and right, and for the latitudes of bottom and top.
Depending on how deformed the map is, the result can be good enough or not. Try to find the exact longitudes and latitudes of the corners of your map, e.g. via Google Maps.
Depending on how you're running your Python program, matplotlib will show an interactive plot. You can zoom to every region, and the axes will adapt. In the bar at the bottom the x and y-positions will be shown. If they are not the desired ones, you can try to change the extents until they match.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread("california_map_blank.png")
dpi = 120
height, width, bands = img.shape
# Update figure size based on image size
figsize = width / float(dpi), height / float(dpi)
# Create a figure of the right size with one axes that takes up the full figure
fig, ax = plt.subplots(figsize=figsize)
# find the extent
longitude_top_left = -124.5
longitude_top_right = -113
latitude_bottom_left = 32
latitude_top_left = 42
extent = [longitude_top_left, longitude_top_right, latitude_bottom_left, latitude_top_left]
# Draw the image
ax.imshow(img, interpolation='nearest', extent=extent)
plt.show()

How to remove white spaces in the graph plot in python?

I have a problem after plotting the graph with matplolib using the python. I got the figure but the figure is having the white spaces of which i don't require. I have read most of the links that were provided by stack overflow but none is regarding to my issue. Now, I want to remove white spaces and require the whole image with picture.
Actually, I am new to the plot in python. I have created a plot of which the black colour is box and the grey colour is the frame.
I created the top vie of the 3D plot this as an image(.png) using the following code.
def cuboid(center, size):
ox, oy, oz = center
l, w, h = size
###Added the fig in order to be able to plot it later
ax = fig.gca(projection='3d') ##plot the project cuboid
X=[ox-l/2,ox-l/2,ox-l/2,ox-l/2,ox+l/2,ox+l/2,ox+l/2,ox+l/2] ##corner points of the cuboid
Y=[oy+w/2,oy-w/2,oy-w/2,oy+w/2,oy+w/2,oy-w/2,oy-w/2,oy+w/2]
Z=[oz-h/2,oz-h/2,oz+h/2,oz+h/2,oz+h/2,oz+h/2,oz-h/2,oz-h/2]
# ax.scatter(X,Y,Z,c='g',marker='o') #the plot before rotated
X_new = ([]) #attaining new corner points after rotated
Y_new = ([])
Z_new = ([])
for i in range(0,8):
c=np.matrix([[X[i]], ##reading every corner points into matrix format
[Y[i]],
[Z[i]]])
u=Rot_Mat*c ##rotating every corner point with the rotation matrix
X_new = np.append(X_new, u.item(0)) ##appending the corner points with the neighbours
Y_new = np.append(Y_new, u.item(1))
Z_new = np.append(Z_new, u.item(2))
print('\nvertex=\n',c)
print('\nnew_vertex=\n',u)
###Doing a dot product between Rot_Mat and c as earlier but using np.dot as it is necessary with Numpy format, reshaping from(3,1) to (3)
side[i,:] = np.dot(Rot_Mat, c).reshape(3)
sides = [[side[0],side[1],side[2],side[3]], ##defining the 6 sides of cuboid
[side[4],side[5],side[6],side[7]],
[side[0],side[1],side[4],side[5]],
[side[2],side[3],side[4],side[5]],
[side[1],side[2],side[5],side[6]],
[side[4],side[7],side[0],side[3]]]
ax.scatter(X_new,Y_new,Z_new,c='blue',marker='') #the plot of corner points after rotated
ax.add_collection3d(Poly3DCollection(sides, facecolors='black', linewidths=1, edgecolors='black', alpha=.25)) ###This draw the plane sides as requred
fig.tight_layout()
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
plt.axis('off') #removes the axes from grams
The initialisation data to create this cuboid plot is given as follows:
fig=plt.figure(figsize=(6,6)) ##to obtain figure and dimensions of graph
ax = fig.add_axes([0,0,1,1], projection='3d')
#plot planes
p = Rectangle((0,-0.7), 4.5,1.4, color="lightgrey", alpha=0.2) #plots the background frame
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")
i=pd.read_excel('Bond0.dump.xlsx') ##to read the excel file format
X=i['x'] ## to import the variable on to axes from data set
Y=i['y']
Z=i['z']
j=pd.read_excel('paketone4000.dump.xlsx') ##to read the excel file format
X=j['x'] ## to import the variable on to axes from data set
Y=j['y']
Z=j['z']
a=j['x']##import centre of mass from excel file format
b=j['y']
c=j['z']
#cuboid initialising parameters
center = [a[0], b[0], c[0]] ##centre of the body
length = 0.3 ##defining length, breadth, height
width = 0.4
height = 0.1
side = np.zeros((8,3)) ###This numpy vector will be used to store the position of the sides
The expected outcome is that i have to remove the white spaces in the picture and form a picture with the grey frame (vertical dimensions=(0,4.5), horizontal dimention=(-0.7,0.7))

Cartopy mixing projections and overplotting image data

I'm trying to overplot some satellite image data on top of a OSM tile.
I can plot them both separately but can't seem to overplot and I think it's down to the projection.
I load the data and get the projection information
ds = gdal.Open(fname)
data = ds.ReadAsArray()
gt = ds.GetGeoTransform()
proj = ds.GetProjection()
data=data.astype(np.float64)
projcs = inproj.GetAuthorityCode('PROJCS')
projection = ccrs.epsg(projcs)
The projection is
_EPSGProjection(32611)
I then set up the plot
subplot_kw = dict(projection=projection)
fig, ax = plt.subplots(figsize=(12, 6), subplot_kw=subplot_kw)
Then get the OSM tile, set up the axes and add it
imagery = OSM()
ax = plt.axes(projection=imagery.crs)
ax.add_image(imagery, 14)
Finally I set the extent of the imagery data and add it with imshow
extent = (gt[0], gt[0] + ds.RasterXSize * gt[1],
gt[3] + ds.RasterYSize * gt[5], gt[3])
img=ax.imshow(data, extent=extent, origin='upper', cmap='jet', vmin=1, vmax=1.3, alpha=0.1, transform=imagery.crs)
This doesn't display the imagery data at all, just the OSM tile.
I think the problem is with the transform keyword but I don't know how to fix it.
The value of the transform argument should be the coordinate system the data you are plotting are represented in. It is not related to the projection you want to visualise on. You are using the OSM coordinate system as the transform for your image data, this is wrong. You should be using the projection you defined for the image via the epsg code.

How do I force scatter points real pixel values when plotting in pyplot/python?

I've taken an image and extracted some features from it using OpenCv. I'd like to replot those points and their respective areas (which are real pixel values) into a scatter window and then save it. Unfortunately, when I plot the points, they resize to stay more visible. If I zoom in they resize. I'd like to save the whole figure retaining the actual ratio of pixel (x,y) coordinates to size of points plotted.
For instance:
import matplotlib.pyplot as plt
x=[5000,10000,20000]
y=[20000,10000,5000]
area_in_pixels=[100,200,100]
scatter(x,y,s=area_in_pixels)
I would like this to produce tiny dots on the image. They should span like 10 xy units. However, the dots it produces are large, and appear to span 1000 xy units.
I've tried resizing the image with:
plt.figure(figsize=(10,10))
Which seems to resize the points relative to their position a little. But I'm not sure what scale I would select to make this accurate. DPI settings on plt.figsave seem to make the saved image larger but don't appear to alter relative spot sizes.
Asked another way, is there another way to relate the s which is in points^2 to a real number or to the units of the x-y axis?
You can use patches to create markers sized relative to the data coordinates.
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
xData=[5000,10000,20000, 15000]
yData=[20000,10000,5000, 15000]
radius_in_pixels=[100,200,100, 1000] # Circle takes radius as an argument. You could convert from area.
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
for x, y, r in zip(xData, yData, radius_in_pixels):
ax.add_artist(Circle(xy=(x, y), radius = r))
plt.xlim(0, max(xData) + 200)
plt.ylim(0, max(yData) + 200)
plt.show()

Categories

Resources