Move an object towards a target in PyBullet - bulletphysics

I'm pretty new to PyBullet and physics engines in general. My first step is trying to get one object to move towards another.
import pybullet as p
import time
import pybullet_data
DURATION = 10000
physicsClient = p.connect(p.GUI)#or p.DIRECT for non-graphical version
p.setAdditionalSearchPath(pybullet_data.getDataPath()) #optionally
print("data path: %s " % pybullet_data.getDataPath())
p.setGravity(0,0,-10)
planeId = p.loadURDF("plane.urdf")
cubeStartPos = [0,0,1]
cubeStartOrientation = p.getQuaternionFromEuler([0,0,0])
boxId = p.loadURDF("r2d2.urdf",cubeStartPos, cubeStartOrientation)
gemId = p.loadURDF("duck_vhacd.urdf", [2,2,1], p.getQuaternionFromEuler([0,0,0]) )
for i in range (DURATION):
p.stepSimulation()
time.sleep(1./240.)
gemPos, gemOrn = p.getBasePositionAndOrientation(gemId)
cubePos, cubeOrn = p.getBasePositionAndOrientation(boxId)
oid, lk, frac, pos, norm = p.rayTest(cubePos, gemPos)[0]
#rt = p.rayTest(cubePos, gemPos)
#print("rayTest: %s" % rt[0][1])
print("rayTest: Norm: ")
print(norm)
p.applyExternalForce(objectUniqueId=boxId, linkIndex=-1, forceObj=pos
,posObj=gemPos, flags=p.WORLD_FRAME)
print(cubePos,cubeOrn)
p.disconnect()
But this just gets R2 to wiggle a bit. How do I do this?

First of all, if you are moving a robot, you should do something a little more complicated, by providing some commands to the joints of the robot. Here is an example
Now assuming that you are moving something less complicated by applying an external force, the simplest thing you can do is multiply a factor alpha with the difference between the two positions; this would be your force.
For your example this would be:
import numpy as np
import pybullet as p
import time
import pybullet_data
DURATION = 10000
ALPHA = 300
physicsClient = p.connect(p.GUI) # or p.DIRECT for non-graphical version
p.setAdditionalSearchPath(pybullet_data.getDataPath()) # optionally
print("data path: %s " % pybullet_data.getDataPath())
p.setGravity(0, 0, -10)
planeId = p.loadURDF("plane.urdf")
cubeStartPos = [0, 0, 1]
cubeStartOrientation = p.getQuaternionFromEuler([0, 0, 0])
boxId = p.loadURDF("r2d2.urdf", cubeStartPos, cubeStartOrientation)
gemId = p.loadURDF("duck_vhacd.urdf", [
2, 2, 1], p.getQuaternionFromEuler([0, 0, 0]))
for i in range(DURATION):
p.stepSimulation()
time.sleep(1./240.)
gemPos, gemOrn = p.getBasePositionAndOrientation(gemId)
boxPos, boxOrn = p.getBasePositionAndOrientation(boxId)
force = ALPHA * (np.array(gemPos) - np.array(boxPos))
p.applyExternalForce(objectUniqueId=boxId, linkIndex=-1,
forceObj=force, posObj=boxPos, flags=p.WORLD_FRAME)
print('Applied force magnitude = {}'.format(force))
print('Applied force vector = {}'.format(np.linalg.norm(force)))
p.disconnect()

Related

How to simulate an object balancing on another in pybullet?

I am trying to simulate a ball balancing on a board with pybullet and openAI gym, but for now I am working with any shapes. I have the gym part down, but I am not sure how to approach this with pybullet. Here is an example of code I wrote up for one object, I want to make that move and balance another object on it. here is the code for the openAI env, and what I have worked on so far to render it with pybullet:
import os import gym import numpy as np import pybullet as pb import pybullet_data import math import random
class BeamEnv(gym.Env):
def __init__(self, obs_low_bounds = np.array([ 0, 0, "TBD", -45]),
obs_high_bounds = np.array([12, 12, "TBD", 45])):
self.physicsClient = pb.connect(pb.GUI) pb.setAdditionalSearchPath(pybullet_data.getDataPath()) self._seed()
"""Environment for a ball and beam system where agent has control of tilt.
Args:
obs_low_bounds (list, optional): [target location(in), ball location(in),
ball velocity(in/s), beam angle(deg)]. Defaults to [ 0, 0, "TBD", -45].
obs_high_bounds (list, optional): As above so below. Defaults to [12, 12, "TBD", 45].
"""
super(BeamEnv, self).__init__()
# Hyperparameters
self.ACC_GRAV = 386.22 # [in/s]
self.MOTOR_SPEED = 46.875 # 1.28[sec/60deg] converted to [deg/s]
self.TIME_STEP = 0.1 # [s]
# Observation Space
# _bounds = []
self.obs_low_bounds = obs_low_bounds
self.obs_high_bounds = obs_high_bounds
self._determine_max_velocity()
self.observation_space = gym.spaces.Box(low = self.obs_low_bounds,
high = self.obs_high_bounds,
dtype = np.float32)
# Action Space
# increase, decrease or keep current angle
self.action_space = gym.spaces.Descrete(3)
# Reward Range
self.reward_range = (-1, 1)
def _set_velocity_bounds(self):
"""Use Inclined Plane and Kinematics Formulas
to determine min/max velocities and set the obs_low/high_bounds
"""
# Max Distance
distance_max = self.obs_high_bounds[1]
# Max Angle
ang_max = self.obs_high_bounds[3]
# Max acceletation (Inclined Plane Formula)
a_max = self.ACC_GRAV * np.sin(np.deg2rad(ang_max))
# Max Velocity (vf^2 = v0^2 + 2ad)
vel_max = np.sqrt(2*a_max*distance_max)
# Set Bounds
self.obs_low_bounds[2] = -vel_max
self.obs_high_bounds[2] = vel_max
def _compute_observation(self): cubePos, cube0rn = pb.getBasePositionAndOrientation(self.botId) cubeEuler = pb.getEulerFromQuaternion(cubeOrn) linear, angular = pb.getBaseVelocity(self.botId) return[cubeEuler[0],angular[0],self.vt]
def _compute_reward(self): _, cubeOrn = pb.getBasePosition(self.botId) cubeEuler = pb.getEulerFromQuaternion(cube0rn) return(1 - abs(cubeEuler[0])) *
0.1 - abs(self.vt - self.vd)
def _compute_done(self): cubePos, _ = pb.getBasePositionAndOrientation(self.botId) return cubePos[2] < 0.15 or self._envStepCounter >= 1500
def reset(self, target_location = None,
ball_location = None):
pb.resetSimulation() pb.setGravity(0,0,-9.8) """default timeStep is 1/240s""" pb.setTimeStep(0.01) planeId = pb.loadURDF('plane.urdf') #loading bot cubeStarPos=[0,0,0.001] cubeStartOrientation = pb.getQuaternionFromEuler([0,0,0]) path = os.path.abspath(os.path.dirname(__file__)) self.botId = pb.loadURDF(os.path.join(path, "beam.xml"), cubeStartPos, cubeStartOrientation) self._observation = self._compute_observation() return np.array(self._observation)
"""Reset the environment so the ball is not moving, there is no angle,
Args:
target_location (float, optional): Desired location of ball. Defaults to random.
ball_location (float, optional): Current location of ball. Defaults to random.
Returns:
list: observation of (target location, ball location, ball velocity, beam angle)
"""
# Set target location
if target_location is not None:
self.target_location = target_location
else:
possible_targets = list(range(self.obs_low_bounds[0], self.obs_high_bounds[0]))
self.target_location = random.choice(possible_targets)
# Set ball location
if ball_location is not None:
self.ball_location = ball_location
else:
possible_ball_locations = list(range(self.obs_low_bounds[1], self.obs_high_bounds[1]))
self.ball_location = random.choice(possible_ball_locations)
# Set Intial Velocity and Angle to Zero
self.ball_velocity = 0 # [in/s]
self.beam_angle = 0 # [deg]
return self._next_observation()
def _next_observation(self):
"""Determines what will happen in the next time step
Returns:
list: observation of (target location, ball location, ball velocity, beam angle)
"""
# Calculate Acceleration (Inclined Plane Equation)
ball_acceleration = self.ACC_GRAV * np.sin(np.deg2rad(self.beam_angle))
# Calculate Next Position (x = x0 + v0t + 0.5at^2)
self.ball_location = self.ball_location + self.ball_velocity * self.TIME_STEP + 0.5 * ball_acceleration * self.TIME_STEP**2
# Calculate New Velocity (v = v0 + at)
self.ball_velocity = self.ball_velocity + ball_acceleration * self.TIME_STEP
# Clip Ball Location
self.ball_location = max(min(self.ball_location,
self.obs_high_bounds[1]),
self.obs_low_bounds[1])
# Clip Ball Velocity
self.ball_velocity = max(min(self.ball_velocity,
self.obs_high_bounds[2]),
self.obs_low_bounds[2])
# Return Observation
return [self.target_location, self.ball_location, self.ball_velocity, self.beam_angle]
def _take_action(self,action):
"""Determines change in angle due to action
Args:
action (int): increase, decrease or keep current angle
"""
# Change action to signs by subtracting by 1 ie (0,1,2) --> (-1,0,1)
action -= 1
# Change the angle by unit step
self.beam_angle = self.beam_angle + action * self.MOTOR_SPEED * self.TIME_STEP
# Clip
self.beam_angle = max(min(self.beam_angle,
self.obs_high_bounds[3]),
self.obs_low_bounds[3])
def step(self, action):
"""Take action, collect reward and get new observation
Args:
action (int): increase, decrease or keep current angle
Returns:
tuple: (observation, reward, done, info)
"""
# Take the action
self._take_action(action)
# Determine Success
if (round(abs((self.target_location - self.ball_location)),3) == 0) & (round(self.ball_velocity, 3) == 0) & (round(self.beam_angle, 3) == 0):
done = True
else:
done = False
# Find Reward
reward = 1 if done else -1
# Find Next Observation
obs = self._next_observation()
# Return what happened
return obs, reward, done, {}
def _seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return[seed]
here is an object in pybullet, the board I will be balancing an object on. I am not sure how to make it move by a variable force or render it based on my openAI gym script.
import numpy
import pybullet as pb
physicsClient = pb.connect(pb.GUI)
> #creates plane import pybullet_data pb.setAdditionalSearchPath(pybullet_data.getDataPath()) planeId =
> pb.loadURDF('plane.urdf')
>
>
> visualShapeId = pb.createVisualShape(
> shapeType=pb.GEOM_MESH,
> fileName='procedural_objects/126/126.obj',
> rgbaColor=None,
> meshScale=[0.1, 0.1, 0.1])
>
> collisionShapeId = pb.createCollisionShape(
> shapeType=pb.GEOM_MESH,
> fileName='procedural_objects/126/126.obj',
> meshScale=[0.1, 0.1, 0.1])
>
> #connects visual shape and collider multiBodyId = pb.createMultiBody(
> baseMass=1.0,
> baseCollisionShapeIndex=collisionShapeId,
> baseVisualShapeIndex=visualShapeId,
> basePosition=[0, 0, 1],
> baseOrientation=pb.getQuaternionFromEuler([0, 0, 0]))
>
> pb.setGravity(0, 0, -9.8) pb.setRealTimeSimulation(1)
> #use setTimeStep fn to override default time step (1/240s)
any advice how to get pybullet to generate a random shape (ignore ball) balancing on another random shape?

How to solve Euler–Bernoulli beam equation in FiPy?

To understand how FiPy works, I want to solve the Euler–Bernoulli beam equation with fixed endpoints:
w''''(x) = q(x,t), w(0) = w(1) = 0, w'(0) = w'(1) = 0.
For simplicity, let q(x,t) = sin(x).
How can I define and solve it in FiPy? How to specify the source term sin(x) with respect to the only independent variable in the equation?
from fipy import CellVariable, Grid1D, DiffusionTerm, ExplicitDiffusionTerm
from fipy.tools import numerix
nx = 50
dx = 1/nx
mesh = Grid1D(nx=nx, dx=dx)
w = CellVariable(name="deformation",mesh=mesh,value=0.0)
valueLeft = 0.0
valueRight = 0.0
w.constrain(valueLeft, mesh.facesLeft)
w.constrain(valueRight, mesh.facesRight)
w.faceGrad.constrain(valueLeft, mesh.facesLeft)
w.faceGrad.constrain(valueRight, mesh.facesRight)
# does not work:
eqX = DiffusionTerm((1.0, 1.0)) == numerix.sin(x)
eqX.solve(var=w)
Here is what seems to be a working version of your problem
from fipy import CellVariable, Grid1D, DiffusionTerm
from fipy.tools import numerix
from fipy.solvers.pysparse.linearPCGSolver import LinearPCGSolver
from fipy import Viewer
import numpy as np
L = 1.
nx = 500
dx = L / nx
mesh = Grid1D(nx=nx, dx=dx)
w = CellVariable(name="deformation",mesh=mesh,value=0.0)
valueLeft = 0.0
valueRight = 0.0
w.constrain(valueLeft, mesh.facesLeft)
w.constrain(valueRight, mesh.facesRight)
w.faceGrad.constrain(valueLeft, mesh.facesLeft)
w.faceGrad.constrain(valueRight, mesh.facesRight)
x = mesh.x
k_0 = 0
k_1 = -1
k_2 = 2 + np.cos(L) - 3 * np.sin(L)
k_3 = -1 + 2 * np.sin(L) - np.cos(L)
w_analytical = numerix.sin(x) + k_3 * x**3 + k_2 * x**2 + k_1 * x + k_0
w_analytical.name = 'analytical'
# does not work:
eqX = DiffusionTerm((1.0, 1.0)) == numerix.sin(x)
eqX.solve(var=w, solver=LinearPCGSolver(iterations=20000))
Viewer([w_analytical, w]).plot()
raw_input('stopped')
After running this, the FiPy solution seems to be quite close to the analytical result.
The two important changes from the OP's implementation.
Using mesh.x which is the correct way to refer to the spatial variable for use in FiPy equations.
Specifying the solver and number of iterations. The problem seems to be slow to converge so needed a lot of iterations. From my experience, fourth order spatial equations often need good preconditioners to converge quickly. You might try using the Trilinos solver package with Fipy to make this work better as it has a wider range of available preconditioners.
Use an explicit float for L to avoid integer maths in Python 2.7 (edit from comment)

Dumping numpy arrays into neural network

I am trying to solve the titanic machine learning challenge from kaggle using a neural network. I removed most of the irrelevant data and converted the useful data into a 2D numpy array while the survival is converted into a 1D numpy array. For some reason it throws an error saying dimension 0 in both shape must be equal, I've been trying to solve it for quite a while and I hope that you guys can help out.
TensorFlowNumpy.py
import tensorflow as tf
def numpy2tensor(numpy):
sess = tf.Session()
with sess.as_default():
return tf.constant(numpy)
def tensor2numpy(tensor):
sess = tf.Session()
with sess.as_default():
return tensor.eval()
Dataset.py
import pandas
import numpy as np
dataset = pandas.read_csv('train.csv')
dataset2= dataset.drop(['PassengerId','Survived','Name','Ticket','Fare','Cabin','Embarked'],axis=1)
dataset3= dataset2.fillna(0)
survive = pandas.read_csv('train.csv')
survival = np.float32(survive.Survived)
dataset4 = np.float32(dataset3)
MainCode.py
import tensorflow as tf
import numpy
from dataset import dataset4,survival
from sklearn.model_selection import train_test_split
from TensorFlowNumpy import numpy2tensor
train_x,test_x,train_y,test_y = train_test_split(dataset4,survival,test_size
= 0.2)
tensor_train_x = numpy2tensor(train_x)
tensor_train_y = numpy2tensor(train_y)
tensor_test_x = numpy2tensor(test_x)
tensor_test_y = numpy2tensor(test_y)
n_nodes_hl1 = 10
n_nodes_hl2 = 10
n_classes = 2
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
def neural_network_model(data):
hidden_1_layer = {'weights':tf.Variable(tf.random_normal([5,
n_nodes_hl1])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1,
n_nodes_hl2])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2,
n_classes])),
'biases':tf.Variable(tf.random_normal([n_classes]))}
l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']),
hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)
l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']),
hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)
output = tf.matmul(l2,output_layer['weights']) + output_layer['biases']
return output
def train_neural_network(x):
prediction = neural_network_model(x)
cost =
tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,
labels=tensor_train_y))
optimizer1 = tf.train.GradientDescentOptimizer(0.001).minimize(cost)
hm_epochs = 100
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(hm_epochs):
epoch_loss = 0
_, c = sess.run([optimizer1, cost], feed_dict={x:tensor_train_x,
y:tensor_train_y})
epoch_loss += c
print('Epoch', epoch+1, 'completed out
of',hm_epochs,'loss:',epoch_loss)
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
print('Accuracy:',accuracy.eval({x:test_x, y:test_y}))
train_neural_network(tensor_train_x)
I have faced this error several times, problem is obviously in our code. I didn't look through your code thoroughly as i am leaving for the day, but i smell that your dependent variable/ output variable shape is [1,712] which should be [712,1] so some where in the code try to fix it. Basically what it meant is you are having one row with 712 columns but it should be 712 rows with 1 column(output). Please mark this as answer if it helps. Ping me tomorrow if problem still exists. I will take a look at it.

Getting different accuracies using different caffe classes(98.65 vs 98.1 vs 98.20)

When I train and then test my model using Caffe's command line interface, I get e.g. 98.65% whereas when I myself write code(given below) to calculate accuracy from the same pre-trained model, I get e.g 98.1% using Caffe.Net.
Everything is straight forward and I have no idea what is causing the issue.
I also tried using Caffe.Classifier and its predict method, and yet get another lesser accuracy(i.e. 98.20%!)
Here is the snippet of code I wrote:
import sys
import caffe
import numpy as np
import lmdb
import argparse
from collections import defaultdict
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import itertools
from sklearn.metrics import roc_curve, auc
import random
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--proto', help='path to the network prototxt file(deploy)', type=str, required=True)
parser.add_argument('--model', help='path to your caffemodel file', type=str, required=True)
parser.add_argument('--mean', help='path to the mean file(.binaryproto)', type=str, required=True)
#group = parser.add_mutually_exclusive_group(required=True)
parser.add_argument('--db_type', help='lmdb or leveldb', type=str, required=True)
parser.add_argument('--db_path', help='path to your lmdb/leveldb dataset', type=str, required=True)
args = parser.parse_args()
predicted_lables=[]
true_labels = []
misclassified =[]
class_names = ['unsafe','safe']
count=0
correct = 0
batch=[]
plabe_ls=[]
batch_size = 50
cropx = 224
cropy = 224
i = 0
multi_crop = False
use_caffe_classifier = True
caffe.set_mode_gpu()
# Extract mean from the mean image file
mean_blobproto_new = caffe.proto.caffe_pb2.BlobProto()
f = open(args.mean, 'rb')
mean_blobproto_new.ParseFromString(f.read())
mean_image = caffe.io.blobproto_to_array(mean_blobproto_new)
f.close()
net = caffe.Classifier(args.proto, args.model,
mean = mean_image[0].mean(1).mean(1),
image_dims = (224, 224))
net1 = caffe.Net(args.proto, args.model, caffe.TEST)
net1.blobs['data'].reshape(batch_size, 3,224, 224)
data_blob_shape = net1.blobs['data'].data.shape
#check and see if its lmdb or leveldb
if(args.db_type.lower() == 'lmdb'):
lmdb_env = lmdb.open(args.db_path)
lmdb_txn = lmdb_env.begin()
lmdb_cursor = lmdb_txn.cursor()
for key, value in lmdb_cursor:
count += 1
datum = caffe.proto.caffe_pb2.Datum()
datum.ParseFromString(value)
label = int(datum.label)
image = caffe.io.datum_to_array(datum).astype(np.float32)
#key,image,label
#buffer n image
if(count % 5000 == 0):
print('{0} samples processed so far'.format(count))
if(i < batch_size):
i+=1
inf= key,image,label
batch.append(inf)
#print(key)
if(i >= batch_size):
#process n image
ims=[]
for x in range(len(batch)):
img = batch[x][1]
#img has c,w,h shape! its already gone through transpose and channel swap when it was being saved into lmdb!
#Method III : use center crop just like caffe does in test time
if (use_caffe_classifier != True):
#center crop
c,w,h = img.shape
startx = h//2 - cropx//2
starty = w//2 - cropy//2
img = img[:, startx:startx + cropx, starty:starty + cropy]
#transpose the image so we can subtract from mean
img = img.transpose(2,1,0)
img -= mean_image[0].mean(1).mean(1)
#transpose back to the original state
img = img.transpose(2,1,0)
ims.append(img)
else:
ims.append(img.transpose(2,1,0))
if (use_caffe_classifier != True):
net1.blobs['data'].data[...] = ims[:]
out_1 = net1.forward()
plabe_ls = out_1['pred']
else:
out_1 = net.predict(np.asarray(ims), oversample=multi_crop)
plabe_ls = out_1
plbl = np.asarray(plabe_ls)
plbl = plbl.argmax(axis=1)
for j in range(len(batch)):
if (plbl[j] == batch[j][2]):
correct+=1
else:
misclassified.append(batch[j][0])
predicted_lables.append(plbl[j])
true_labels.append(batch[j][2])
batch.clear()
i = 0
sys.stdout.write("\rAccuracy: %.2f%%" % (100.*correct/count))
sys.stdout.flush()
print(", %i/%i corrects" % (correct, count))
What is causing this difference in accuracies ?
More information :
I am using Python3.5 on windows.
I read images from an lmdb dataset.
The images have 256x256 and center cropped with the size 224x224.
It is finetuned on GoogleNet.
For the Caffe.predict to work well I had to change classify.py
In training, I just use Caffes defaults, such as random crops at training and center crop at test-time.
Changes:
changed line 35 to:
self.transformer.set_transpose(in_, (2, 1, 0))
and line 99 to :
predictions = predictions.reshape((len(predictions) // 10, 10, -1))
1) First off, you need to revert Line 35 (32?) of classify.py: self.transformer.set_transpose(in_, (2, 1, 0)) back to the original
self.transformer.set_transpose(in_, (2, 0, 1)). So it expects HWC and transforms internally to CHW for downstream processing.
2) Run your Classifier branch as it is. You're likely to get a bad result. Please check this. If so, it means the image database is not CWH as you've commented, but actually CHW. After you've confirmed this, make the change to your Classifier branch: ims.append(img.transpose(2,1,0)) to become ims.append(img.transpose(1,2,0)). Re-test your Classifier branch. The result should be 98.2% (goto Step 3) or 98.65% (try Step 4).
3) If your result in Step 3 is 98.2%, also undo your the second change to classify.py. Theoretically, as your images have even height/width so // and / should have no difference. If it does differ or crashes, something is seriously wrong with your image database -- your assumption of the image size is incorrect. You need to check these. They could be off by a pixel or so, and could explain the slight discrepancies in accuracy.
4) If your result in Step 3 is 98.65%, then you need to make changes to the Caffe.Net branch of your code. The database images are CHW, so you need to make the first transpose: img = img.transpose(1,2,0) and the second transpose after mean subtraction to img = img.transpose(2,0,1). Then run your Caffe.Net branch. If you still get 98.1% as before, you should check that mean subtraction is performed correctly by your network.
In Steps (2) and (4), it's possible to get worse results, which means that the problem is likely a difference in mean subtraction for your trained Net vs your expectations in Python code. Check this.
About your 98.2% for the caffe.Classifier:
If you look at lines 78 - 80, the center crop is done along crop_dims , not img_dims. If you further look at line 42 on the caffe.Classifier constructor, the crop_dims are never user-determined. It's determined by the size of the Net's input blobs. Lastly, it you look at line 70, the img_dims are used to resize the images prior to center cropping. So what's happening with your setup is: a) The images are first getting resized to 224 x 224, then uselessly getting center cropped to 224 x 224 ( I assume this is the HxW for your Net ). You obviously will get results poorer than 98.65%. What you need to do is to change the img_dims = (256, 256). That prevents resizing. The crop will be picked up automatically from your Net and you should get your 98.65%.

Constant Runtime Error -Python - Tkinter

My problem here is that I get a Runtime Error every time I run my code. Also, I am unable to bind my "Repeat" button with the "RUN" function. I do not understand why the button will not work and I am also unsure why the "self.canvas.delete()" does not work and why the new frame does not open when the puzzle has been solved (when all of the disks have been moved to a new pole) and why it opens straight away.
from Tkinter import *
import sys
import time
def Hanoi(n, src, dst, tmp, move):
if n == 0:
return n
else:
Hanoi(n-1, src, tmp, dst, move)
move(src, dst)
Hanoi(n-1, tmp, dst, src, move)
class hanoi():
master = Tk()
width = 2000
height = 400
time = 0.1
big_sep = 30
small_sep = 5
def __init__(self):
self.User_Input = input("Please enter the amount of disks")
self.canvas = Canvas(hanoi.master, height = hanoi.height, width = hanoi.width)
self.canvas.pack()
self.poles = [[], [], []]
self.Add_Objects()
def Add_Objects(self):
floor_size = 1000-2*hanoi.small_sep
self.disk_height = (400 - 4*hanoi.big_sep) / self.User_Input
self.disk_width = (floor_size - 4*hanoi.small_sep) / 3
disk_h = self.disk_height
disk_w = self.disk_width
global disk_h
global disk_w
width = hanoi.width
height = hanoi.height
small_sep = hanoi.small_sep
big_sep = hanoi.big_sep
#create poles
bar_pos = [ 4*small_sep + disk_w/2 + (disk_w+small_sep)*i for i in range(0,3) ]
for x in bar_pos:
print x
self.canvas.create_rectangle(x-small_sep, big_sep, x+small_sep, 400-big_sep-1, fill='black')
#create bases
for x in bar_pos:
print i
self.canvas.create_rectangle(x-(13*small_sep), 370, x+(13*small_sep), 410, fill = "brown")
#create disks
for i in range(self.User_Input):
print 2*small_sep + 4*small_sep*i, height-big_sep-1-disk_h*i,2*small_sep + disk_w - 4*small_sep*i, height-big_sep-1-disk_h*(i+1)
disk = self.canvas.create_rectangle(2*small_sep + 4*small_sep*i, 400-big_sep-1-disk_h*i,2*small_sep + disk_w - 4*small_sep*i, 400-big_sep-1-disk_h*(i+1),fill='blue')
self.poles[0].append(disk)
self.canvas.update()
def Move_Object(self, origin, dest):
print len(self.poles[dest]), self.User_Input-1
current_disk = self.poles[origin].pop()
self.poles[dest].append(current_disk)
x_distance = (dest - origin) * (disk_w)
y_distance = ((len(self.poles[origin]) - len(self.poles[dest])+1) * disk_h)
self.canvas.move(current_disk, x_distance, y_distance)
self.canvas.update()
time.sleep(hanoi.time)
if len(self.poles[dest]) == self.User_Input:
self.canvas.delete()
new_frame = Frame(hanoi.master, width = 300, height = 300)
new_frame.pack()
print "Yayar"
newb = Button(new_frame, text = "Replay", )
newb.place(relx = 0.5, rely = 0.5)
newb.bind("<ButtonPress-1>", self.RUN)
def RUN(self):
Hanoi(self.User_Input, 0, 2, 1, self.Move_Object)
if __name__ == "__main__":
print "hello"
hanoi().RUN()