So here's my problem. I'm using ROS and opencv, trying to create a depth map using two cameras. However, the code that i wrote, does not seem to do anything and im a little confused about why. (previous codes that i've been running had the same structure)
#!/usr/bin/env python
from __future__ import print_function
import roslib
roslib.load_manifest('test_cam')
import sys
import rospy
import cv2
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import message_filters
class image_converter:
def __init__(self):
self.bridge = CvBridge()
self.image_sub_1 = message_filters.Subscriber("/cameras/left_hand_camera/image",Image)
self.image_sub_2 = message_filters.Subscriber("/cameras/head_camera/image",Image)
self.ts = message_filters.TimeSynchronizer([self.image_sub_1, self.image_sub_2], 10)
self.ts.registerCallback(self.callback)
def callback(self,Image):
try:
cv_image_1 = self.bridge.imgmsg_to_cv2(Image, "bgr8")
cv_image_2 = self.bridge.imgmsg_to_cv2(Image, "bgr8")
except CvBridgeError as e:
print(e)
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)
disparity = stereo.compute(cv_image_1,cv_image_2)
plt.imshow(disparity,'gray')
plt.show()
plt.waitKey(1)
def main(args):
ic = image_converter()
rospy.init_node('image_converter', anonymous=True)
try:
rospy.spin()
except KeyboardInterrupt:
print("Shutting down")
cv2.destroyAllWindows()
if __name__ == '__main__':
main(sys.argv)
You must execute rospy.init before subscribing to any topic.
Related
import os
import sys
import json
import requests
import isodate
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
bufsize=1024
session = requests.Session()
session.trust_env=False
path = os.getcwd()
print(path)
format(os.getcwd())
os.chdir('/raj')
file_name = pd.read_excel('repos_desc12_p61qr.xlsx')
file2 = open("commit_details.csv", "w+", buffering=bufsize)
file3 = open("merge_details.csv", "w+", buffering=bufsize)
hostname = "https://bsp-os.git.visteon.com"
private = "-rBpd_x15GRTmFkk_T9H"
def excel_parser(meExcel):
dict_format = meExcel.to_dict(orient='record')
#print(dict_format.columns.ravel())
#dict_format = json.loads(dict_format)
#print(dict_format)
for repo_detail in dict_format:
parsed_repo_path = repo_detail["REPO"]
#print(parsed_repo_path)
parsed_branch_name = repo_detail["BranchName"]
#print(parsed_branch_name)
parsed_duration = repo_detail["StartDate"]
while am trying to run and take input through pipeline , the " EOFError: EOF when reading a line " is occuring i tried error exception but not working please help to get the input from python file through jenkins pipeline
I would like to compare log and pct change f the two symbols, but the following error appears:
KeyError: 'Adj Close'
import datetime
import pandas as pd
import numpy as np
import yfinance as yf
start = datetime.datetime(2017, 10, 1)
end = datetime.datetime.now()
symbols = ['BTC-USD', 'ETH-USD']
df = pd.DataFrame()
for i in symbols:
data = yf.download(i, start=None, end=None,show_errors=("True"),
period="4y", interval="1mo")
df[i] = data['Adj Close'].pct_change().dropna()
df['log_stuff'] = \
np.log(df['Adj Close'].astype('float64')/df['Adj Close'].astype('float64').shift(1))
df[['pct_change', 'log_stuff','df']].plot();
You could try the following. Please note, that you can also pass a list to download(), so no loops are required.
import numpy as np
import pandas as pd
import yfinance as yf
symbols = ['BTC-USD', 'ETH-USD']
data = yf.download(symbols, period="4y", interval="1mo")
# calculate pct return
pct_data = data['Adj Close'].pct_change()
pct_data = pct_data.add_suffix('_pct')
# calculate log returns
log_data = np.log(data['Adj Close']) - np.log(data['Adj Close'].shift(1))
log_data = log_data.add_suffix('_log')
# combine returns and drop na values
combined_data = pd.concat([pct_data,log_data], axis=1).dropna()
print(combined_data)
This will yield the following output:
BTC-USD_pct ETH-USD_pct BTC-USD_log ETH-USD_log
Date
2017-12-01 0.383326 0.692483 0.324490 0.526197
2018-01-01 -0.277987 0.477813 -0.325713 0.390564
2018-02-01 0.017298 -0.235276 0.017150 -0.268240
...
I would like to record multiple meshcat visualizers with different prefix ids so I can eventually save them to an HTML file that I can interact with later. I would like the different visualizations to play on top of each other and to be able to select/unselect different visualizations.
Here is a minimal replication of the problem. I expect there to be two cartpole visualizations that are on top of each other. However, I only end up seeing one of them being recorded. The other cartpole seems stuck at the end position when I play back the recording
import meshcat
from pydrake.common import FindResourceOrThrow
from pydrake.multibody.plant import (
AddMultibodyPlantSceneGraph)
from pydrake.multibody.parsing import Parser
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.meshcat_visualizer import (
ConnectMeshcatVisualizer,
)
v = meshcat.Visualizer()
file_name = FindResourceOrThrow(
"drake/examples/multibody/cart_pole/cart_pole.sdf")
builder = DiagramBuilder()
cart_pole, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0)
Parser(plant=cart_pole).AddModelFromFile(file_name)
cart_pole.Finalize()
vis = ConnectMeshcatVisualizer(builder=builder,
prefix="vis",
scene_graph=scene_graph,
open_browser=False)
vis2 = ConnectMeshcatVisualizer(
builder=builder,
prefix="vis2",
scene_graph=scene_graph,
open_browser=False)
vis2.set_name("vis2")
diagram = builder.Build()
diagram_context = diagram.CreateDefaultContext()
cart_pole_context = diagram.GetMutableSubsystemContext(
cart_pole, diagram_context)
cart_pole.get_actuation_input_port().FixValue(cart_pole_context, .02)
simulator = Simulator(diagram, diagram_context)
simulator.set_publish_every_time_step(False)
vis.start_recording()
vis2.start_recording()
simulator.AdvanceTo(100)
vis.stop_recording()
vis2.stop_recording()
vis.publish_recording()
vis2.publish_recording()
# f = open("saved.html", "w")
# f.write(v.static_html())
# f.close()
Here is one solution. I don't love it, but it accomplishes the stated goal. Note the changes:
saving and publishing only one animation
naming the model in the MultibodyPlant with a distinct name for each sim
setting delete_prefix_on_load=False so it doesn't clear the old geometry
import meshcat
from pydrake.common import FindResourceOrThrow
from pydrake.multibody.plant import (AddMultibodyPlantSceneGraph)
from pydrake.multibody.parsing import Parser
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.meshcat_visualizer import (
ConnectMeshcatVisualizer,
)
animation = None
for i in range(3):
file_name = FindResourceOrThrow(
"drake/examples/multibody/cart_pole/cart_pole.sdf")
builder = DiagramBuilder()
cart_pole, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0)
Parser(plant=cart_pole).AddModelFromFile(file_name, f"plant{i}")
cart_pole.Finalize()
vis = ConnectMeshcatVisualizer(builder=builder,
scene_graph=scene_graph,
delete_prefix_on_load=False,
open_browser=False)
if animation:
vis._animation = animation
diagram = builder.Build()
diagram_context = diagram.CreateDefaultContext()
cart_pole_context = diagram.GetMutableSubsystemContext(
cart_pole, diagram_context)
cart_pole.get_actuation_input_port().FixValue(cart_pole_context, .02)
simulator = Simulator(diagram, diagram_context)
simulator.set_publish_every_time_step(False)
vis.start_recording()
simulator.AdvanceTo(10)
vis.stop_recording()
animation = vis._animation
vis.publish_recording()
after simulating this code of federated learning for image classification, I would like to save my model so I add this two lines
ckpt_manager = FileCheckpointManager("model.h5")
ckpt_manager.save_checkpoint(ServerState.from_anon_tuple(state), round_num=2)
So here is all my code:
import collections
import time
import tensorflow as tf
tf.compat.v1.enable_v2_behavior()
import tensorflow_federated as tff
source, _ = tff.simulation.datasets.emnist.load_data()
def map_fn(example):
return collections.OrderedDict(
x=tf.reshape(example['pixels'], [-1, 784]), y=example['label'])
def client_data(n):
ds = source.create_tf_dataset_for_client(source.client_ids[n])
return ds.repeat(10).shuffle(500).batch(20).map(map_fn)
train_data = [client_data(n) for n in range(10)]
element_spec = train_data[0].element_spec
def model_fn():
model = tf.keras.models.Sequential([
tf.keras.layers.Input(shape=(784,)),
tf.keras.layers.Dense(units=10, kernel_initializer='zeros'),
tf.keras.layers.Softmax(),
])
return tff.learning.from_keras_model(
model,
input_spec=element_spec,
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
trainer = tff.learning.build_federated_averaging_process(
model_fn, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(0.02))
....
NUM_ROUNDS = 11
for round_num in range(2, NUM_ROUNDS):
state, metrics = trainer.next(state, federated_train_data)
print('round {:2d}, metrics={}'.format(round_num, metrics))
ckpt_manager = FileCheckpointManager("model.h5")
ckpt_manager.save_checkpoint(ServerState.from_anon_tuple(state), round_num=9)
But this error does appear:
NameError: name 'FileCheckpointManager' is not defined
I will appreciate it if you told me how I solve this problem
Looks like the code is missing an import for the module with the checkpoint manager.
FileCheckpointManger is defined in the checkpoint_manager module here: tensorflow_federated/python/research/utils/checkpoint_manager.py.
Try adding an import at the top of the file like this (the following example assumes the tensorflow federated github repo is in the import search path):
from tensorflow_federated.python.research.utils import checkpoint_manager
# ...
ckpt_manager = checkpoint_manager.FileCheckpointManager("model.h5")
I am beginner of python language,natural language processing,deep learning,neural networks.I want to execute a program which convert text file into vector by using word2vec in python..someone please help me
import math
import nltk file = "/home/stephy/Demo/textfile.txt"
import numpy as np
def loadGloveModel(gloveFile):
with open(gloveFile, encoding="utf8" ) as f:
content = f.readlines()
model = {} for line in content:
splitLine = line.split()
word = splitLine[0]
embedding = np.array([float(val) for val in splitLine[1:]])
model[word] = embedding
print ("Done.",len(model)," words loaded!")
return model
model= loadGloveModel(file)
print (model['file'])