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).
Related
I am using the Spyder IDE(5.3.3) with python(3.9.13 64bit) on Ubuntu 20.04LTS. I am trying to plot errorbar by calculating the standard deviation between '5' sets of data. My x-coordinate is named 'RC_AVG', y-coordinate is named 'PMF_AVG' and, the standard deviation is named 'PMF_STD'. After storing data in these lists, I've reshaped all of them to shape (175,1) and then I am using the ax.errorbar command to plot the errorbars but python throws 'Value error': 'yerr' (shape: (175, 1)) must be a scalar or a 1D or (2, n) array-like whose shape matches 'y' (shape: (175, 1)). I am unable to understand the cause of this error and need help in understanding it. However, when I remove the reshape(175,1) from the x,y and, the error coordinates the code works fine and I get the graph. I am attaching the code below:
typeimport numpy as np
import matplotlib.pyplot as plt
fig, (ax1) = plt.subplots(1,1,figsize=(5,5))
file_name = "bsResult-THETA83-IRUN"
result = []
for i in range(1,6):
a = np.array(np.loadtxt(file_name+str(i)+".xvg", dtype = float,skiprows=18,max_rows=175))
result.append(a)
result = np.array(result)
result1 = result.copy()
RC_AVG = np.mean(result1[:,:,0],axis=0).reshape(175,1) ###### x-coordinate
PMF_AVG = np.mean(result1[:,:,1],axis=0).reshape(175,1) ##### y-coordinate
PMF_STD = np.std(result1[:,:,2],axis=0).reshape(175,1) ###### error-coordinate
ax1.set_xlim(0.1,1.70)
ax1.set_xlabel("\u03B6 $(nm)$",fontweight = 'bold',fontsize=12)
ax1.set_ylabel("G $(k_{B}T)$",fontweight = 'bold',fontsize=12)
ax1.errorbar(RC_AVG,PMF_AVG,yerr=PMF_STD,label = 'Nitrogen',color='#D32D41',linewidth=1.0,elinewidth=1.0,
capsize=1.1,ecolor='black',errorevery=(8))
#####################################################################
Traceback (most recent call last):
File "/home/sps/software/yes/lib/python3.9/site-packages/spyder_kernels/py3compat.py", line 356, in compat_exec
exec(code, globals, locals)
File "/media/sps/hdd/PMF/REFERENCE/pmf-2G6X6-epswdr-wspce-k400/pmfReference.py", line 31, in <module>
ax1.errorbar(RC_AVG,PMF_AVG,yerr=PMF_STD,label = 'Nitrogen',color='#D32D41',linewidth=1.0,elinewidth=1.0,
File "/home/sps/software/yes/lib/python3.9/site-packages/matplotlib/__init__.py", line 1423, in inner
return func(ax, *map(sanitize_sequence, args), **kwargs)
File "/home/sps/software/yes/lib/python3.9/site-packages/matplotlib/axes/_axes.py", line 3588, in errorbar
raise ValueError(
ValueError: 'yerr' (shape: (175, 1)) must be a scalar or a 1D or (2, n) array-like whose shape matches 'y' (shape: (175, 1)) here
I am able to get the errorbars in the plot if I remove the reshape(175,1) from the x,y and, the error coordinates as shown below:
import matplotlib.pyplot as plt
fig, (ax1) = plt.subplots(1,1,figsize=(5,5))
file_name = "bsResult-THETA83-IRUN"
result = []
for i in range(1,6):
a = np.array(np.loadtxt(file_name+str(i)+".xvg", dtype = float,skiprows=18,max_rows=175))
result.append(a)
result = np.array(result)
result1 = result.copy()
RC_AVG = np.mean(result1[:,:,0],axis=0)#.reshape(175,1) ----commented reshape
PMF_AVG = np.mean(result1[:,:,1],axis=0)#.reshape(175,1) ---commented reshape
PMF_STD = np.std(result1[:,:,2],axis=0)#.reshape(175,1) ----commented reshape
ax1.set_xlim(0.1,1.70)
ax1.set_xlabel("\u03B6 $(nm)$",fontweight = 'bold',fontsize=12)
ax1.set_ylabel("G $(k_{B}T)$",fontweight = 'bold',fontsize=12)
ax1.errorbar(RC_AVG,PMF_AVG,yerr=PMF_STD,label = 'Nitrogen',color='#D32D41',linewidth=1.0,elinewidth=1.0,
capsize=1.1,ecolor='black',errorevery=(8))
type here
[enter image description here](https://www.stackoverflow.com/)
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from random import random
#Show Images
image_show = True
#Parameters ( mm )
square_size = 50
room_width = 5000
room_length = 10000
n_guess = 50 # number of random points generated
max_cell_value = 255 # highest number in a cell.
#Handy functions for conversions
def mm2grid( mm):
return int(mm/square_size)
def grid2mm( grid):
return int(grid*square_size)
def rotation( theta):
return np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])
# Build a simple empty map
map_floor = np.zeros((mm2grid(room_width), mm2grid(room_length)),)
# NOTE: Any cell >0 is considered occupied
print("Map size= {} cells".format( map_floor.shape))
# Set border walls
map_floor[ 0, :] = 255
map_floor[-1, :] = 255
map_floor[ :, 0] = 255
map_floor[ :,-1] = 255
#Draw something in the centre
map_floor[20:80,100:120] = 100
### Target Position ###
target = np.array([2500,0])
### Robot Position ###
x = np.array([1000,1000, np.pi*0])
# Randomly generate n_number of positions #
x_rand = np.zeros(( 3, n_guess))
for k in range( n_guess):
x_rand[:,k] = np.array([ random()*room_width, random()* room_length, random()*3.14159])
#remove any points inside a solid object
if map_floor[ int(mm2grid( x_rand[0,k])), int(mm2grid( x_rand[1,k]))] > 0:
x_rand[:,k] = 0
### TODO ###
#for n_number calculate angle to target#
#for n_number calculate distance measurement to nearest wall.
#### Display Map ####
# Remember: images are printed y inverted and x first.
if image_show:
# Draw Map
plt.matshow( max_cell_value-map_floor, cmap=plt.cm.gray) # max_cell_value is just to correct color scheme
# Draw randomly positioned squares on the map
plt.plot( [mm2grid( x_rand[1,:])], [mm2grid(x_rand[0,:])],'rx')
# Draw Robot position
plt.plot( [mm2grid( x[1])], [mm2grid(x[0])], 'b8', markersize=12)
plt.plot( [mm2grid( x[1]), mm2grid( x[1]+ 300*np.cos(x[2]))],\
[mm2grid( x[0]), mm2grid( x[0]+ 300*np.sin(x[2]))], 'b-', linewidth=2.5)
plt.text( mm2grid( x[1]), mm2grid( x[0]+300), 'Robot', color='b')
# Draw target
plt.plot( [mm2grid( target[1])],[mm2grid( target[0])], 'g>', markersize=30)
plt.text( mm2grid( target[1]), mm2grid( target[0] - 250), 'Target', color='g')
# Draw line from robot to target
plt.plot( [mm2grid( x[1]), mm2grid(target[1])],\
[mm2grid( x[0]), mm2grid(target[0])], 'k--')
# Show everything.
plt.show()
I am not sure how to fix the error.
in line 48 I changed xrange to range I also did some other things to some other places to fix and error I was getting in line 26 and it was saying
TypeError: 'float' object cannot be interpreted as an index
But it looks like I have fixed those problems but I am not sure if I have messed something up somewhere and now it is giving me this error:
Map size= (100, 200) cells
Traceback (most recent call last):
File "/Users/oscarwallace/Downloads/Map.py", line 64, in <module>
plt.plot( [mm2grid( x_rand[1,:])], [mm2grid(x_rand[0,:])],'rx')
File "/Users/oscarwallace/Downloads/Map.py", line 19, in mm2grid
return int(mm/square_size)
TypeError: only size-1 arrays can be converted to Python scalars
I was wondering if anyone knew what I have to do to sop this from happening. Thanks in advance.
This error occurs when you're trying to cast into an integer something that isn't just one scalar. For instance, a ndarray with two elements. This is an example of this error:
import numpy as np
int(np.array([1, 3]))
TypeError: only size-1 arrays can be converted to Python scalars
What you can do is use .astype(int)
(mm/square_size).astype(int)
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.
I'm trying to pick random zone in an image using numpy.
I'm using a python set to ensure that all my zones are unique, however, later when trying to generate a mask from this set, I'm getting an "SyntaxError: invalid syntax"
here is the code I'm using:
def _get_positions(self):
small_shape = int(self._width / MACROPIXEL_SIZE)
small_mask = numpy.zeros((small_shape, small_shape), dtype=numpy.uint8)
#how many macropixel we will pick
nb_pick = int((small_shape * small_shape) * self._alter_percentage)
position_set = set()
#try again until we pick 'nb_pick' unique positions
while len(position_set) < nb_pick:
pick = numpy.random.choice(small_shape, 2)
position_set.add((pick[0], pick[1]))
# mark the selected pixels
{small_mask[pos_x][pos_y]=1 for (pos_x, pos_y) in position_set}
# full size mask
self.mask = numpy.kron(small_mask, numpy.ones(self._height, self._width))
code explanation:
I need to process a lot of images, so I'm trying to optimize my code
I'm trying to pick random zones using a simpler version of this image (this is the 'small shape' and 'small mask').
when the set is full of unique positions, I'm using it to mark on the mask which part of the image where selected
and at last, I'm rescaling the mask
why the set comprehension give a syntax error ? what am I doing wrong ?
--edit--
error trace:
Traceback (most recent call last):
File "test_random_alteration.py", line 27, in <module>
import alter_labels
File "/home/abgrall/segmentation/loreal/histo_erp_fm/alter_labels.py", line 56
{small_mask[pos_x][pos_y]=1 for (pos_x, pos_y) in position_set}
^
SyntaxError: invalid syntax
You can not the set comprehension that you are using here
{small_mask[pos_x][pos_y]=1 for (pos_x, pos_y) in position_set}
these comprehensions are for creating sets of objects. You are using it to assign a value to an array - which is invalid syntax.
Instead,
for pos_x, pos_y in position_set:
small_mask[pos_x][pos_y] = 1
However, if you are trying to make this more efficient, you can complitly vectorize your random selection of the pos_x, pos_y pairs and vectorize the access on small_mask.
def _get_positions(self):
small_shape = int(self._width / MACROPIXEL_SIZE)
small_mask = numpy.zeros((small_shape, small_shape), dtype=numpy.uint8)
#how many macropixel we will pick
nb_pick = int((small_shape * small_shape) * self._alter_percentage)
nx, ny = small_shape, small_shape
xy = np.mgrid[:nx,:ny].reshape(2, -1).T
pos = xy.take(np.random.choice(xy.shape[0], nb_pick, replace=False), axis=0)
small_mask[pos] = 1
self.mask = numpy.kron(small_mask, numpy.ones(self._height, self._width))
I'm trying to make a program that goes through an image that simulates a line of text and grabs each letter from it. Thinking of the image of a 2D array of pixels, if there exist black pixels in consecutive columns, those columns will be written to a buffer. Once a column with no black pixels has been reached (i.e. space between letters) the buffer will be turned in to an image of the letter that has been detected. However, I'm getting a compiler error that I don't understand that I hope you guys can help me with. Hopefully you'll also catch on to any logic errors I haven't recognized.
Anyway, code:
from PIL import Image
import numpy as np
class ShapeDetect:
def __init__(self):
self.img = Image.open("test3.jpg")
self.pixels = self.img.load()
self.l = np.empty([0, 0])
self.valid_pixels = ['(0, 0, 0)', '(1, 1, 1)', '(2, 2, 2)', '(3, 3, 3)', '(4, 4, 4)', '(5, 5, 5)']
def printPixels(self):
for i in range(self.img.size[0]):
for j in range(self.img.size[1]):
print(self.pixels[i, j])
def processPixels(self):
n = 1
# If a black pixel is in the current column, add it to l
for i in range (self.img.size[0]):
for j in range(self.img.size[1]):
if str(self.pixels[i, j]) in self.valid_pixels:
self.writeColumn(i)
break
# Once a whole shape has been written to l, make l into an image
else:
if self.l.size > 0 and j == self.img.size[1] - 1:
new_img = Image.new(self.img.mode, (self.l.size, 100))
new_img.putdata(self.l)
new_img.save(str(n) + ".jpg")
n = n + 1
self.l = np.empty([0], [0])
def writeColumn(self, n):
# put column in pixels in temp, then append temp to l
temp = np.zeros((1, self.img.size[1]), dtype=np.int64)
for i in range(self.img.size[1]):
temp[0, i], = (self.pixels[n, i])
np.append(self.l, temp, axis = 1)
if __name__ == "__main__":
shapeDetect = ShapeDetect()
ShapeDetect.processPixels(shapeDetect)
The error I get is:
Traceback (most recent call last):
File "SD.py", line 46, in <module>
ShapeDetect.processPixels(shapeDetect)
File "SD.py", line 23, in processPixels
self.writeColumn(i)
File "SD.py", line 40, in writeColumn
temp[0, i], = (self.pixels[n, i])
ValueError: too many values to unpack
The error happened because self.pixels[n, i] returns a pixel, which have 3 values.
Looks like you have actually want all 3 values, but you had mistakenly placed a comma after temp[0,i]. Removing the comma would fix the issue.
However, there is a quicker way to extract the column. You can replace
temp = np.zeros((1, self.img.size[1]), dtype=np.int64)
for i in range(self.img.size[1]):
temp[0, i], = (self.pixels[n, i])
with
temp = self.pixels[n, :]
for numpy arrays