This is a "working example" that does not work. Why does this not run? scipy seems to not work.
i get this error:
File "display_map.py", line 35, in
rot_cw = R.from_quat(keyframe["rot_cw"]).as_matrix()
AttributeError: 'Rotation' object has no attribute 'as_matrix'
please can someone help me me change it. I tried reducing the version of scipy
import msgpack
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from numpy.linalg import inv
from scipy.spatial.transform import Rotation as R
import open3d as o3d
import sys
if len(sys.argv) < 2:
print(
"ERROR: Please provide path to .msg file. Example usage is; python3 visualize_openvslam_map.py path_to.msg"
)
exit()
with open(sys.argv[1], "rb") as f:
upacked_msg = msgpack.Unpacker(f)
packed_msg = upacked_msg.unpack()
keyfarmes = packed_msg["keyframes"]
landmarks = packed_msg["landmarks"]
# FILL IN KEYFRAME POINTS(ODOMETRY) TO ARRAY
keyframe_points = []
keyframe_points_color = []
for keyframe in keyfarmes.values():
# get conversion from camera to world
trans_cw = np.matrix(keyframe["trans_cw"]).T
rot_cw = R.from_quat(keyframe["rot_cw"]).as_matrix()
# compute conversion from world to camera
rot_wc = rot_cw.T
trans_wc = -rot_wc * trans_cw
keyframe_points.append((trans_wc[0, 0], trans_wc[1, 0], trans_wc[2, 0]))
keyframe_points = np.array(keyframe_points)
keyframe_points_color = np.repeat(np.array([[0., 1., 0.]]),
keyframe_points.shape[0],
axis=0)
# FILL IN LANDMARK POINTS TO ARRAY
landmark_points = []
landmark_points_color = []
for lm in landmarks.values():
landmark_points.append(lm["pos_w"])
landmark_points_color.append([
abs(lm["pos_w"][1]) * 4,
abs(lm["pos_w"][1]) * 2,
abs(lm["pos_w"][1]) * 3
])
landmark_points = np.array(landmark_points)
landmark_points_color = np.array(landmark_points_color)
# CONSTRUCT KEYFRAME(ODOMETRY) FOR VISUALIZTION
keyframe_points_pointcloud = o3d.geometry.PointCloud()
keyframe_points_pointcloud.points = o3d.utility.Vector3dVector(keyframe_points)
keyframe_points_pointcloud.colors = o3d.utility.Vector3dVector(
keyframe_points_color)
# CONSTRUCT LANDMARK POINTCLOUD FOR VISUALIZTION
landmark_points_pointcloud = o3d.geometry.PointCloud()
landmark_points_pointcloud.points = o3d.utility.Vector3dVector(landmark_points)
landmark_points_pointcloud.colors = o3d.utility.Vector3dVector(
landmark_points_color)
# VISULIZE MAP
o3d.visualization.draw_geometries([
keyframe_points_pointcloud, landmark_points_pointcloud,
o3d.geometry.TriangleMesh.create_coordinate_frame()
])
In scipy.spatial.Rotation methods from_dcm, as_dcm were renamed to from_matrix, as_matrix respectively.
Related
I am trying to calculate the pressure force F=pressure*length (because in 2D) on a wing profile.
I used the example of the MEDCOUPLING agitator, but I can't adapt it correctly.
It seems to me that I have to :
-retrieve the mesh from the corresponding .med
-retrieve the corresponding pressure field
-make it an array
The problem is that :
-I can't get the edge of the airfoil to measure it
-I can't determine and select the pressures applying to this edge
-I can't determine and select the pressures that apply to this edge. In your opinion, should I first extract the cells corresponding to the edge and then extract the corresponding pressure, or do you see other possibilities?
Thanks
import system
import salome
import medcoupling as mc
import numpy as np
salome.salome_init()
import salome_notebook
notebook = salome_notebook.NoteBook()
sys.path.insert(0, r'/home/b72882/Documents')
import GEOM
from salome.geom import geomBuilder
import math
import SALOMEDS
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
ailMesh2DMc=mc.ReadUMeshFromFile("naca10.med", "MeshFlow10", 0)
m2DSurf,desc,descI,revDesc,revDescI = ailMesh2DMc.buildDescendingConnectivity()
nbOf2DCellSharing = revDescI.deltaShiftIndex()
ids2 = nbOf2DCellSharing.findIdsEqual(1)
ailSkinMc = m2DSurf[ids2]
f = mc.MEDCouplingFieldDouble.New(mc.ON_CELLS, mc.ONE_TIME)
f.setTime(1,200,201)
f.setArray(ailMesh2DMc.computeCellCenterOfMass())
f.setMesh(ailMesh2DMc)
f.setName("Pressure")
mc.WriteField("naca10.med",f,True)
f2 = mc.ReadFieldCell("naca10.med", f.getMesh().getName(), 0, f.getName(), 200, 201)
arr = f2.getArray()
arr=mc.DataArrayDouble(ailMesh2DMc.getNumberOfCells(),1)
ids = arr.findIdsInRange(-6.,6.)
pressOnAilMc = f2[ids]
offsetsOfTupleIdsInField = revDescI[ids]
tupleIdsInField = revDesc[offsetsOfTupleIdsInField]
pressOnSkinAilMc = pressOnAilMc[tupleIdsInField]
pressOnSkinAilMc.setMesh(ailSkinMc)
pressSkin = pressOnAilMc.getArray()
pressSkin *= 1e5
areaSkin = ailSkinMc.getMeasureField(True).getArray()
forceSkin = pressSkin*areaSkin
normalSkin = ailSkinMc.buildOrthogonalField().getArray()
forceVectSkin = forceSkin*normalSkin
# mesh1d,lskin,di,r,ri = ailMesh2DMc.explodeIntoEdges()
force = forceVectSkin/lSkin
I'm trying to use the OpenCV Python wrapper to calculate the Discrete wavelet Haar transform for an image. Supposedly, images == numpy arrays == CV matrices, so I thought this should work:
import cv2
import numpy as np
import pywt
from pywt import wavedec
import csv
imgcv1 = cv2.split(resize)[0]
cv2.boxFilter(imgcv1, 0, (7,7), imgcv1, (-1,-1), False, cv2.BORDER_DEFAULT)
cv2.resize( imgcv1, (32, 32 ) ,imgcv1)
imf = np.float32(imgcv1)/255.0 # float conversion/scale
coeffs = pywt.dwt(imf, "haar") # the dwt
cA = coeffs
#imgout = pywt.dwt(coeffs, "haar")
print(cA)
def zigzag(matrix):
rows=len(matrix)
columns=len(matrix[0])
solution=[[] for i in range(rows+columns-1)]
for i in range(rows):
for j in range(columns):
sum=i+j
if(sum%2 ==0):
solution[sum].insert(0,matrix[i][j])
else:
solution[sum].append(matrix[i][j])
data = (rows*columns)/3
data = round(data)
mtx_zigzag = []
for i in solution:
for j in i:
mtx_zigzag.append(j)
mtxawal = mtx_zigzag[2:26]
# mtxtengah = mtx_zigzag[83:107]
# mtxakhir = mtx_zigzag[191:215]
mtx = mtxawal
# +mtxtengah+mtxakhir
return mtx
hasil_zigzag= zigzag(cA)
print(hasil_zigzag)
zg=[]
zg.append(hasil_zigzag)
citra="tangan {}".format(counter)
file=open('database.csv','a+',newline='')
with file:
write=csv.writer(file)
write.writerows(zg)
the excel /csv data output is like this:
I want the matrix or csv/excel output to be like this:
can you guys help me
I am using open3d to render a 3D head together with a hairstyle (see code below). I am now looking for a way to take a screenshot of the rendered objects. How do you suggest proceeding? I need to consider a few hundred hairstyles, so I would prefer to avoid using mouse or keyboard control.
All 3D objects (head and hairstyle) are from this dataset.
This is the script I'm using to visualize the 3D head model and the hairstyle:
import open3d as o3d
import math
from mathutils import Vector
import struct
import array
import numpy as np
# Load the head model
mesh = o3d.io.read_triangle_mesh("../head_model.obj")
# Load a 3D hairstyle
fin = open("../strands00144.data", "rb")
num_of_strands = struct.unpack('i', fin.read(4))[0]
hair = []
num_strand = 0
#print("num_of_strands: ", num_of_strands)
for i in range(num_of_strands):
num_of_vertices = struct.unpack('i', fin.read(4))[0]
if num_of_vertices == 100:
num_strand += 1
#print("num_of_vertices: ", num_of_vertices)
strand = []
for j in range(num_of_vertices):
vertex_x = struct.unpack('f', fin.read(4))[0]
vertex_y = struct.unpack('f', fin.read(4))[0]
vertex_z = struct.unpack('f', fin.read(4))[0]
vertex = [vertex_x, vertex_y, vertex_z]
#print("vertex: ", vertex)
strand.append(vertex)
hair.append(strand)
randomPoints = np.zeros([100*num_strand, 3])
for ii in range(num_strand):
randomPoints[0 + 100 * ii: 100 + 100 * ii][:] = hair[ii][:][:]
o3d.visualization.Visualizer()
pointSet = o3d.geometry.PointCloud()
pointSet.points = o3d.utility.Vector3dVector(randomPoints)
pointSet.paint_uniform_color([0, 0, 0])
mesh.compute_vertex_normals()
o3d.visualization.draw_geometries([pointSet, mesh])
what i am trying is masking a value from nc file with numpy array, according to specific location but it gives me 1d array and i can not use this array for plotting here my code.
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma
file = './sample_data/NSS.AMBX.NK.D08214.S0740.E0931.B5312324.WI.nc'
data = Dataset(file,mode='r')
fcdBT89gHz = np.asarray(data.groups['Data_Fields']['fcdr_brightness_temperature_1'][:])
fcdBT150gHz = np.asarray(data.groups['Data_Fields']['fcdr_brightness_temperature_2'][:])
fcdBT183_1gHz = np.asarray(data.groups['Data_Fields']['fcdr_brightness_temperature_3'][:])
fcdBT183_3gHz = np.asarray(data.groups['Data_Fields']['fcdr_brightness_temperature_4'][:])
fcdBT183_7gHz = np.asarray(data.groups['Data_Fields']['fcdr_brightness_temperature_5'][:])
lats = data.groups['Geolocation_Time_Fields']['latitude'] #Enlem degerleri
lons = data.groups['Geolocation_Time_Fields']['longitude'] #Boylam degerleri
latlar = np.asarray(lats[:]) # Lati
lonlar = np.asarray(lons[:]) # Long
lo = ma.masked_outside(lonlar,105,110)
la = ma.masked_outside(latlar,30,35)
merged_coord=~ma.mask_or(la.mask,lo.mask)
h = plt.plot(fcdBT150gHz[merged_coord])
The output is like that but i need latitudes in x axis like this plot
If you need shape of variables:
lo.shape = (2495, 90)
la.shape = (2495, 90)
fcdBT150gHz[merged_coord].shape = (701,)
Maybe i did not use true way for masking. If data is needed here.
I am new to both python and librosa. I am trying to follow this method for a speech recognizer: acoustic front end
My code:
import librosa
import librosa.display
import numpy as np
y, sr = librosa.load('test.wav', sr = None)
normalizedy = librosa.util.normalize(y)
stft = librosa.core.stft(normalizedy, n_fft = 256, hop_length=16)
mel = librosa.feature.melspectrogram(S=stft, n_mels=32)
melnormalized = librosa.util.normalize(mel)
mellog = np.log(melnormalized) - np.log(10**-5)
The problem is that when I apply librosa.util.normalize to variable mel, I expect values to be between 1 and -1, which they aren't. What am I missing?
If you want your output to be log-scaled and normalized to between -1 and +1, you should log-scale first, then normalize:
import librosa
import librosa.display
import numpy as np
y, sr = librosa.load('test.wav', sr = None)
normalizedy = librosa.util.normalize(y)
stft = librosa.core.stft(normalizedy, n_fft = 256, hop_length=16)
mel = librosa.feature.melspectrogram(S=stft, n_mels=32)
mellog = np.log(mel + 1e-9)
melnormalized = librosa.util.normalize(mellog)
# use melnormalized