I'm trying to build an autonomous driving car with the Raspberry Pi - Therefore I try to learn from Udacity's Nanodegree examples.
The following Code is from some GitHub repositories and I just changed the code to work with the PI-CAM. Because the Udacity example Codes work all with .mp4 videos.
When I try to run the following code on the Raspberry PI with the Thonny IDE, sometimes it works for a few seconds or a minute and sometimes it won't even start running.
You can see the whole program here.
def draw_lines(img, lines, thickness=5):
global rightSlope, leftSlope, rightIntercept, leftIntercept
rightColor=[0,0,255]
leftColor=[255,0,0]
#this is used to filter out the outlying lines that can affect the average
#We then use the slope we determined to find the y-intercept of the filtered lines by solving for b in y=mx+b
for line in lines:
for x1,y1,x2,y2 in line:
slope = (y1-y2)/(x1-x2)
if slope > 0.3:
if x1 > 500 :
yintercept = y2 - (slope*x2)
rightSlope.append(slope)
rightIntercept.append(yintercept)
else: None
elif slope < -0.3:
if x1 < 600:
yintercept = y2 - (slope*x2)
leftSlope.append(slope)
leftIntercept.append(yintercept)
...
lines are defined in this part:
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
"""
`img` should be the output of a Canny transform.
"""
lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
draw_lines(line_img, lines)
return line_img
def linedetect(img):
return hough_lines(img, 1, np.pi/180, 10, 20, 100)
This is the error I get when I execute the code :
/usr/local/lib/python3.5/dist-packages/numpy/core/fromnumeric.py:3118: RuntimeWarning: Mean of empty slice.
out=out, **kwargs)
/usr/local/lib/python3.5/dist-packages/numpy/core/_methods.py:85: RuntimeWarning: invalid value encountered in double_scalars
ret = ret.dtype.type(ret / rcount)
version1_for_PI.py:160: RuntimeWarning: divide by zero encountered in int_scalars
slope = (y1-y2)/(x1-x2)
Traceback (most recent call last):
File "/home/pi/Desktop/version-1/version1_for_PI.py", line 244, in <module>
myline = hough_lines(canny, 1, np.pi/180, 10, 20, 5)
File "/home/pi/Desktop/version-1/version1_for_PI.py", line 209, in hough_lines
draw_lines(line_img, lines)
File "/home/pi/Desktop/version-1/version1_for_PI.py", line 158, in draw_lines
for line in lines:
TypeError: 'NoneType' object is not iterable
Your "lines" parameter is None - which is not an "iterable" typed object in python (such as lists, sets, etc).
You should either make sure that the "lines" you pass to the method are not None - or add some logic to ignore it:
if not lines: # means that lines == None
return 0 # or return something else
Another good option is to capture an exception and handle it properly.
Related
I am producing some animation frames in tuples, which may contain (0,0) value, which I would like omit while producing frames with moviepy. The xy contains the following in a loop. The first and second iteration contains (0,0) and the rest contains floats. I would like ignore those iteration that possesses (0,0). Can it be done with moviepy's make_frame(t) def? I need some suggestions.
(0, 0)
(0, 0)
(82.5, 82.5)
(82.5, 82.5)
(108.28125, 108.28125)
(108.28125, 108.28125)
I am getting the following errors:
Traceback (most recent call last):
File "C:\vhosts\VIDEO_TWO_CLONE\vapory-examples-master\scene9.py", line 151, in <module>
clip = VideoClip(make_frame, duration=5)
File "C:\Anaconda64\lib\site-packages\moviepy\video\VideoClip.py", line 103, in __init__
self.size = self.get_frame(0).shape[:2][::-1]
AttributeError: 'NoneType' object has no attribute 'shape'
Process terminated with an exit code of 1
Here is the def of the make_frame(t):
def make_frame(t):
# PREPARE A DRAWING SURFACE
surface = gizeh.Surface(width=W, height=H, bg_color=(0,0,0)) # in pixels
p = PointAnimation((0,0), (110,110), tween=['easeOutElastic', 1, 0.2])
xy = p.make_frame(t, 0.2, 1, 4, 5)
if str(xy) == '(0,0)':
circle = gizeh.circle(r=30, xy=xy, fill=(1,1,0))
circle.draw(surface) # draw the circle on the surface
return surface.get_npimage()
clip = VideoClip(make_frame, duration=5)
clip.write_gif("circle.gif", fps=25, fuzz=10)
In your code, you have if str(xy) == '(0,0)', when in fact this should be if str(xy) == '(0, 0)' (note the space inside the tuple; this is how tuples are converted to strings in Python). However, an even better way to do this is if xy == (0,0) (the space doesn't matter here because there's no conversion to string).
I taught myself the Metropolis Algorithm and decided to try code it in Python. I chose to simulate the Ising model. I have an amateur understanding of Python and with that here is what I came up with -
import numpy as np, matplotlib.pyplot as plt, matplotlib.animation as animation
def Ising_H(x,y):
s = L[x,y] * (L[(x+1) % l,y] + L[x, (y+1) % l] + L[(x-1) % l, y] + L[x,(y-1) % l])
H = -J * s
return H
def mcstep(*args): #One Monte-Carlo Step - Metropolis Algorithm
x = np.random.randint(l)
y = np.random.randint(l)
i = Ising_H(x,y)
L[x,y] *= -1
f = Ising_H(x,y)
deltaH = f - i
if(np.random.uniform(0,1) > np.exp(-deltaH/T)):
L[x,y] *= -1
mesh.set_array(L.ravel())
return mesh,
def init_spin_config(opt):
if opt == 'h':
#Hot Start
L = np.random.randint(2, size=(l, l)) #lxl Lattice with random spin configuration
L[L==0] = -1
return L
elif opt =='c':
#Cold Start
L = np.full((l, l), 1, dtype=int) #lxl Lattice with all +1
return L
if __name__=="__main__":
l = 15 #Lattice dimension
J = 0.3 #Interaction strength
T = 2.0 #Temperature
N = 1000 #Number of iterations of MC step
opt = 'h'
L = init_spin_config(opt) #Initial spin configuration
#Simulation Vizualization
fig = plt.figure(figsize=(10, 10), dpi=80)
fig.suptitle("T = %0.1f" % T, fontsize=50)
X, Y = np.meshgrid(range(l), range(l))
mesh = plt.pcolormesh(X, Y, L, cmap = plt.cm.RdBu)
a = animation.FuncAnimation(fig, mcstep, frames = N, interval = 5, blit = True)
plt.show()
Apart from a 'KeyError' from a Tkinter exception and white bands when I try a 16x16 or anything above that, it looks and works fine. Now what I want to know is if this is right because -
I am uncomfortable with how I have used FuncAnimation to do the Monte Carlo simulation AND animate my mesh plot - does that even make sense?
And How about that cold start? All I am getting is a red screen.
Also, please tell me about the KeyError and the white banding.
The 'KeyError' came up as -
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1540, in __call__
return self.func(*args)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 590, in callit
func(*args)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 147, in _on_timer
TimerBase._on_timer(self)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 1305, in _on_timer
ret = func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 1049, in _step
still_going = Animation._step(self, *args)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 855, in _step
self._draw_next_frame(framedata, self._blit)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 873, in _draw_next_frame
self._pre_draw(framedata, blit)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 886, in _pre_draw
self._blit_clear(self._drawn_artists, self._blit_cache)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 926, in _blit_clear
a.figure.canvas.restore_region(bg_cache[a])
KeyError: <matplotlib.axes._subplots.AxesSubplot object at 0x7fd468b2f2d0>
You are asking a lot of questions at a time.
KeyError: cannot be reproduced. It's strange that it should only occur for some array sizes and not others. Possibly something is wrong with the backend, you may try to use a different one by placing those lines at the top of the script
import matplotlib
matplotlib.use("Qt4Agg")
white bands: cannot be reproduced either, but possibly they come from an automated axes scaling. To avoid that, you can set the axes limits manually
plt.xlim(0,l-1)
plt.ylim(0,l-1)
Using FuncAnimation to do the Monte Carlo simulation is perfectly fine. f course it's not the fastest method, but if you want to follow your simulation on the screen, there is nothing wrong with it. One may however ask the question why there would be only one spin flipping per time unit. But that is more a question on the physics than about programming.
Red screen for cold start: In the case of the cold start, you initialize your grid with only 1s. That means the minimum and maximum value in the grid is 1. Therefore the colormap of the pcolormesh is normalized to the range [1,1] and is all red. In general you want the colormap to span [-1,1], which can be done using vmin and vmax arguments.
mesh = plt.pcolormesh(X, Y, L, cmap = plt.cm.RdBu, vmin=-1, vmax=1)
This should give you the expected behaviour also for the "cold start".
I am using python ODE to solve Van der Pol equation. What I want to do is to find the number of times the ODE's derivatives is called during one invocation of integrate(t) method. The solver I am using is isoda. I am trying to find the number of times the derivatives is called during one invocation without the jacbian function and the number of times the jacobian function is called when I include the jacobian function.
def modified_vanderpol_integrator_demo(dt_min=1e-3, dt_max=10., mu=100.):
# define a class to store the number of calls
class F:
def __init__(self):
self.callsydot = 0
self.callsjac = 0
def ydot(self,t, y, mu):
self.callsydot += 1
x, v = y[0], y[1]
return array([v, mu*(1- x*x)*v - x])
def jac(self, t, y, mu):
self.callsjac += 1
return array([[0, 1], [2*mu*v*x - 1, mu*(1-x*x)]])
Dt = linspace(dt_min, dt_max, 1000)
Num_of_times1 = []
Num_of_times2 = []
for dt in Dt:
xinitial = array([1.0, 2.0]) # initial value
f1 = F()
r1 = ode(f1.ydot)
r1.set_integrator('lsoda')
r1.set_initial_value(xinitial)
r1.set_f_params(mu)
r1.integrate(dt)
Num_of_times1.append(f1.callsydot)
f2 = F()
r2 = ode(f2.ydot, f2.jac)
r2.set_integrator('lsoda', with_jacobian=True)
r2.set_initial_value(xinitial)
r2.set_f_params(mu)
r2.integrate(dt)
Num_of_times2.append(f2.callsjac)
plt.plot(Dt, Num_of_times1)
plt.plot(Dt, Num_of_times2)
plt.show()
When I run this script, I got the message
create_cb_arglist: Failed to build argument list (siz) with enough arguments (tot-opt) required by user-supplied function (siz,tot,opt=2,3,0).
Traceback (most recent call last):
File "stiffequations.py", line 118, in <module>
modified_vanderpol_integrator_demo(dt_min=1e-3, dt_max=10., mu=100.)
File "stiffequations.py", line 111, in modified_vanderpol_integrator_demo
r2.integrate(dt)
File "/usr/local/lib/python2.7/dist-packages/scipy/integrate/_ode.py", line 394, in integrate
self.f_params, self.jac_params)
File "/usr/local/lib/python2.7/dist-packages/scipy/integrate/_ode.py", line 1193, in run
y1, t, istate = self.runner(*args)
lsoda.error: failed in processing argument list for call-back jac.
Why this happens and how to fix it?
Thanks.
I have found out what is wrong with my script. I forget to set the parameters in the jacobian equation.
r2.set_jac_params(mu)
I'm trying to run the code below, where Bwavelength, throughput and newflux are lists.
def ABconversion(Bwavelength, throughput):
ABconstant=[]
c=3e18
i=0
for i in range(0, len(Bwavelength)):
ABconstant.append(((3e18/((Bwavelength[i])**2))*throughput[i]))
i+=1
print len(Bwavelength), len(ABconstant), ABconstant
a=Bwavelength[0]
b=Bwavelength[-1]
h=((b-a)/len(Bwavelength))
ABflux = numpy.trapz(Bwavelength, ABconstant, h)
return ABflux
def ABmagnitude(newflux, ABflux):
ABmagarray=[]
for i in range(len(newflux)):
ABmag = -2.5*log10((newflux[i])/ABflux) - 48.6
ABmagarray.append(ABmag)
return ABmagarray
ABflux1 = ABconversion(Bwavelength, throughput)
print ABflux1
ABmagarray = ABmagnitude(z, ABflux1)
print epoch, ABmagarray
z is defined earlier in the file and is also a list.
However, when I run this I get the message:
Traceback (most recent call last):
File "Rewrite17.11.2014.py", line 196, in <module>
ABflux1 = ABconversion(Bwavelength, throughput)
File "Rewrite17.11.2014.py", line 186, in ABconversion
ABflux = numpy.trapz(Bwavelength, ABconstant, h)
File "C:\Python27\lib\site-packages\numpy\lib\function_base.py, line 3234, in trapz
ret = add.reduce(d * (y[slice1]+y[slice2]/2.0, axis)
ValueError: Operands could not be broadcast together with shapes (0,) (444,)
I don't quite understand the error (I'm fairly new to programming), but I think it means the two "shapes" don't have the same dimensions. I'm not sure why this is.
Thanks in advance.
According to this documentation the parameters to trapz(y, x, dx, axis) are:
y - Array like - input array to integrate.
x - Optional array - If x is None, then spacing between all y elements is dx.
dx - Optional scalar - If x is None, spacing given by dx is assumed. Default is 1.
axis - Optional Int - specify the axis.
So you shouldn't specify both x and dx - one of them should be None.
Perhaps this is what you want: trapz(Bwavelength, None, h).
See this answer for more details on the error message and NumPy's "braodcasting rule".
Replace:
numpy.trapz(Bwavelength, ABconstant, h)
with:
numpy.trapz(np.array(Bwavelength)[:,np.newaxis], ABconstant, h)
I'm trying to produce contour plots for parameters with physical limits using the Minuit2 minimizer which is a part of the ROOT data analysis framework. Unfortunately, Minuit2 seems intent on drifting the parameters into regions outside of their limits when I try to produce contour plots:
>>> from minuit2 import Minuit2
>>> def f(x,y):
... if x < 0 or y < 0:
... print 'x = %.2f, y = %.2f' % (x,y)
... raise Exception
... return x**2 + y**2
...
>>> m = Minuit2(f)
>>> m.limits['x'] = 0, 10
>>> m.limits['y'] = 0, 10
>>> m.migrad()
>>> xy = m.contour('x','y',3)
Info in <Minuit2>: MnMinos UP value has changed, need to update FunctionMinimum class
x = -9.95, y = 0.00
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in f
Exception
Has anybody else dealt with this or a similar problem? Are there any workarounds?
I've already asked this question on the ROOT forums, but I thought there might also be some stack overflow users who have dealt with this or a similar issue.
Try your example without raising an exception
def f(x,y):
return x ** 2 + y ** 2
and you will get reasonable xy contour points (i.e. within 1e-3 of the true contour).
Note that the parameter sigmas=3 in your contour call m.contour('x', 'y', 3) means that the contour for sigmas ** 2 == 9 will be computed and that contour points along the parameter limits are computed. As far as I can see this is not mentioned in the contour() pyminuit documentation).
In your example the contour starts at (0, 0), goes up to (3, 0), along the circle to (0, 3), and back to (0, 0).
A common method is to implement parameter limits (arbitrary shapes, not only min / max) in your cost function by returning very high values for excluded parameters:
def f(x,y):
if x < 0 or y < 0:
return 1e10
return x ** 2 + y ** 2
This does throw the optimizer out of the forbidden regions, but it does not prevent it to probe them sometimes (i.e. evaluate f there).
I don't know why contour() should strictly respect the limits you set via
m.limits['x'] = 0, 10
m.limits['y'] = 0, 10
Here's a short description of the contour algorithm used by Minuit (and Minuit2) and here is the documentation for the Minuit2 code in ROOT, I did not manage to find the actual C file showing the implementation.