I have an image read in with python and I wish to add some different sine stripes on this image as a noise. I wish the frequency and the rotation degree of a sine is totally random. I tried numpy module but it might not be the model I need here.
Can anyone tell me any python module has such function to add random sine curve to a image?
The result should somewhat similar to this image below:
Finally I find I can finish all of this using Numpy module:
def sineimg(img, color='black', linewidth=1.5, linestyle="-"):
'''
frequency = X / random.uniform(10.0, 20.0)
amplitude = randint(35, 50)
phase = random.uniform(1.0, 16.0)
rotation = random.uniform(-pi / 2, pi / 2)
'''
#Random rotation angle
rot = random.randint(-90, 90)
x_ = img.shape[0] / np.cos(np.pi * rot / 180)
X = np.linspace(-1 * x_, x_, 512)
axes = plt.subplot(111)
np.cos(np.pi * rot / 180)
#Random amplitude
amp1 = random.randint(35, 50)
amp2 = random.randint(35, 50)
#Random frequency
frequency1 = X / random.uniform(10.0, 20.0)
frequency2 = X / random.uniform(10.0, 20.0)
#Random offset phase
phase1 = np.pi / random.uniform(1.0, 16.0) + np.pi / 2
phase2 = np.pi / random.uniform(1.0, 16.0) + np.pi / 3
#random distance between line cluster
distance = random.randint(90, 115)
#I need roughly 8 times of them
for i in range(8):
Y1 = amp1 * np.sin(frequency1 + phase1) - 450 + i * distance
Y2 = amp2 * np.sin(frequency2 + phase2) - 420 + i * distance
x1_trans = X * np.cos(np.pi * rot / 180) - Y1* np.sin(np.pi * rot / 180)
y1_trans = X * np.sin(np.pi * rot / 180) + Y1* np.cos(np.pi * rot / 180)
x2_trans = X * np.cos(np.pi * rot / 180) - Y2* np.sin(np.pi * rot / 180)
y2_trans = X * np.sin(np.pi * rot / 180) + Y2* np.cos(np.pi * rot / 180)
#Remove label
axes.set_xticks([])
axes.set_yticks([])
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
axes.spines['bottom'].set_color('none')
axes.spines['left'].set_color('none')
axes.plot(x1_trans, y1_trans, color = color, linewidth=linewidth, linestyle=linestyle)
axes.plot(x2_trans, y2_trans, color = color, linewidth=linewidth, linestyle=linestyle)
plt.imshow(img, zorder=0, extent=[148, -148, -225, 225])
Them:
img=mpimg.imread('me.jpg')
sineimg(img)
I get images like:
Related
I need to generate a double 3D gyroid structure. For this, I'm using vedo
from matplotlib import pyplot as plt
from scipy.constants import speed_of_light
from vedo import *
import numpy as np
# Paramters
a = 5
length = 100
width = 100
height = 10
pi = np.pi
x, y, z = np.mgrid[:length, :width, :height]
def gen_strut(start, stop):
'''Generate the strut parameter t for the gyroid surface. Create a linear gradient'''
strut_param = np.ones((length, 1))
strut_param = strut_param * np.linspace(start, stop, width)
t = np.repeat(strut_param[:, :, np.newaxis], height, axis=2)
return t
plt = Plotter(shape=(1, 1), interactive=False, axes=3)
scale=0.5
cox = cos(scale * pi * x / a)
siy = sin(scale * pi * y / a)
coy = cos(scale * pi * y / a)
siz = sin(scale * pi * z / a)
coz = cos(scale * pi * z / a)
six = sin(scale * pi * x / a)
U1 = ((six ** 2) * (coy ** 2) +
(siy ** 2) * (coz ** 2) +
(siz ** 2) * (cox ** 2) +
(2 * six * coy * siy * coz) +
(2 * six * coy * siz * cox) +
(2 * cox * siy * siz * coz)) - (gen_strut(0, 1.3) ** 2)
threshold = 0
iso1 = Volume(U1).isosurface(threshold).c('silver').alpha(1)
cube = TessellatedBox(n=(int(length-1), int(width-1), int(height-1)), spacing=(1, 1, 1))
iso_cut = cube.cutWithMesh(iso1).c('silver').alpha(1)
# Combine the two meshes into a single mesh
plt.at(0).show([cube, iso1], "Double Gyroid 1", resetcam=False)
plt.interactive().close()
The result looks quite good, but now I'm struggling with exporting the volume. Although vedo has over 300 examples, I did not find anything in the documentation to export this as a watertight volume for 3D-Printing. How can I achieve this?
I assume you mean that you want to extract a watertight mesh as an STL (?).
This is a non trivial problem because it is only well defined on a subset of the mesh regions where the in/out is not ambiguous, in those cases fill_holes() seems to do a decent job..
Other cases should be dealt "manually". Eg, you can access the boundaries with mesh.boundaries() and try to snap the vertices to a closest common vertex. This script is not a solution, but I hope can give some ideas on how to proceed.
from vedo import *
# Paramters
a = 5
length = 100
width = 100
height = 10
def gen_strut(start, stop):
strut_param = np.ones((length, 1))
strut_param = strut_param * np.linspace(start, stop, width)
t = np.repeat(strut_param[:, :, np.newaxis], height, axis=2)
return t
scale=0.5
pi = np.pi
x, y, z = np.mgrid[:length, :width, :height]
cox = cos(scale * pi * x / a)
siy = sin(scale * pi * y / a)
coy = cos(scale * pi * y / a)
siz = sin(scale * pi * z / a)
coz = cos(scale * pi * z / a)
six = sin(scale * pi * x / a)
U1 = ((six ** 2) * (coy ** 2) +
(siy ** 2) * (coz ** 2) +
(siz ** 2) * (cox ** 2) +
(2 * six * coy * siy * coz) +
(2 * six * coy * siz * cox) +
(2 * cox * siy * siz * coz)) - (gen_strut(0, 1.3) ** 2)
iso = Volume(U1).isosurface(0).c('silver').backcolor("p5").lw(1).flat()
cube = TessellatedBox(n=(length-1, width-1, height-1)).c('red5').alpha(1)
cube.triangulate().compute_normals()
cube.cut_with_mesh(iso).compute_normals()
print(iso.boundaries(return_point_ids=True))
print(cube.boundaries(return_point_ids=True))
print(iso.boundaries().join().lines())
show(iso, cube).close()
merge(iso, cube).clean().backcolor("p5").show().close()
iso.clone().fill_holes(15).backcolor("p5").show().close()
I want to "animate" a circle rolling over the sin graph, I made a code where the circle moves rapidly down a straight line, now I want the same but the acceleration will be changing.
My previous code:
import numpy as np
import matplotlib.pyplot as plt
theta = np.arange(0, np.pi * 2, (0.01 * np.pi))
x = np.arange(-50, 1, 1)
y = x - 7
plt.figure()
for t in np.arange(0, 4, 0.1):
plt.plot(x, y)
xc = ((-9.81 * t**2 * np.sin(np.pi / 2)) / 3) + (5 * np.cos(theta))
yc = ((-9.81 * t**2 * np.sin(np.pi / 2)) / 3) + (5 * np.sin(theta))
plt.plot(xc, yc, 'r')
xp = ((-9.81 * t**2 * np.sin(np.pi / 2)) / 3) + (5 * np.cos(np.pi * t))
yp = ((-9.81 * t**2 * np.sin(np.pi / 2)) / 3) + (5 * np.sin(np.pi * t))
plt.plot(xp, yp, 'bo')
plt.pause(0.01)
plt.cla()
plt.show()
You can do this by numerically integrating:
dt = 0.01
lst_x = []
lst_y = []
t = 0
while t < 10: #for instance
t += dt
a = get_acceleration(function, x)
x += v * dt + 0.5 * a * dt * dt
v += a * dt
y = get_position(fuction, x)
lst_x.append(x)
lst_y.append(y)
This is assuming the ball never leaves your slope! If it does, you'll also have to integrate in y in a similar way as done in x!!
Where your acceleration is going to be equal to g * cos(slope).
I have written the following python code to create an animation of a rotating graph using python turtle. The problem I am facing is that, the animation is not properly synchronizing. I don't want to show the people exactly how the thing is rotating. So, I have to carefully choose the frame rate in the turtle.tracer command. Well, if you observe carefully, each value of r creates a rotation, so I must update the screen at the end of each r. And for each value of r, there are 1202 iterations inside the loop for r. But this does not produce the desired effect.
What must I do to correct this?
import turtle
import math
am = turtle
am.ht()
am.tracer(1202,0)
for r in range(0,600):
#axes
am.pu()
am.setpos(0,500)
am.pd()
am.setpos(0,-500)
am.pu()
am.setpos(-650,0)
am.pd()
am.setpos(0,0)
am.write("0",align="right",font=("Times New Roman",14,"normal"))
am.setpos(650,0)
am.pu()
am.setpos(-300*math.cos(r*math.pi/100),300*math.sin(r*math.pi/100))
am.pd()
#axes
am.pencolor("red")
for x in range(-300,301):
g=math.sin(x)
t=math.cos(x)
y =100*g*t*math.sin(2*(x**2)*math.pi/100)
am.setpos(x*math.cos(r*math.pi/100)+y*math.sin(r*math.pi/100),-x*math.sin(r*math.pi/100)+y*math.cos(r*math.pi/100))
#if(x%4==0):
#am.write(x)
am.pu()
am.setpos(-300*math.sin(r*math.pi/100),-300*math.cos(r*math.pi/100))
am.pd()
am.pencolor("blue")
for y in range(-300,301):
c=math.sin(y)
d=math.cos(y)
x =100*c*d*math.cos(2*(y**2)*math.pi/100)
am.setpos(x*math.cos(r*math.pi/100)+y*math.sin(r*math.pi/100),-x*math.sin(r*math.pi/100)+y*math.cos(r*math.pi/100))
am.reset()
am.exitonclick()
I believe the following will do what you desire. I've changed the tracer logic to be more manual with an explicit .update() when you're ready to show the user something. I've also separated the axis drawing from the main loop as we really don't need to clear and redraw it each time:
import math
from turtle import Turtle, Screen
screen = Screen()
screen.tracer(0)
# axes
axes = Turtle(visible=False)
axes.pu()
axes.setpos(0, 500)
axes.pd()
axes.setpos(0, -500)
axes.pu()
axes.setpos(-650, 0)
axes.pd()
axes.setpos(0, 0)
axes.write("0", align="right", font=("Times New Roman", 14, "normal"))
axes.setpos(650, 0)
am = Turtle(visible=False)
for r in range(0, 600):
am.pu()
am.setpos(-300 * math.cos(r * math.pi / 100), 300 * math.sin(r * math.pi / 100))
am.pd()
am.pencolor("red")
for x in range(-300, 301):
g = math.sin(x)
t = math.cos(x)
y = 100 * g * t * math.sin(2 * x**2 * math.pi / 100)
am.setpos(x * math.cos(r * math.pi / 100) + y * math.sin(r * math.pi / 100), -x * math.sin(r * math.pi / 100) + y * math.cos(r * math.pi / 100))
am.pu()
am.setpos(-300 * math.sin(r * math.pi / 100), -300 * math.cos(r * math.pi / 100))
am.pd()
am.pencolor("blue")
for y in range(-300, 301):
c = math.sin(y)
d = math.cos(y)
x = 100 * c * d * math.cos(2 * y**2 * math.pi / 100)
am.setpos(x * math.cos(r * math.pi / 100) + y * math.sin(r * math.pi / 100), -x * math.sin(r * math.pi / 100) + y * math.cos(r * math.pi / 100))
screen.update()
am.reset()
am.hideturtle() # made visible by reset()
screen.exitonclick()
Finally, this was likely an error:
am = turtle
and not doing what you think it was (module name alias instead of an actual turtle.)
How can I add a marking along a plot at the position of -20 degrees true anomaly and 103 degrees true anomaly?
What I have is a trajectory of a space craft along a hyperbolic path around Earth where I solved for the time it took to fly between the true anomalies. Unfortunately, I don't know way to mark a position at a specified angle on the path.
I know I can do
initial = pylab.Circle((location), radius = 10, color = '#000000')
final = ....
but what do I put for the location coordinates? Is there a way to do this without the brute force method of solving for the coordinates?
import numpy as np
import pylab
a = -35000 # the semi-major axis of the hyperbolic trajectory
e = 1.2 # the eccentricity
nu0 = -20 * np.pi / 180 # initial anomaly
nuf = 103 * np.pi / 180 # final anomaly
F0 = 2 * np.arctanh(np.sqrt((e - 1) / (e + 1)) * np.tan(nu0 / 2))
Ff = 2 * np.arctanh(np.sqrt((e - 1) / (e + 1)) * np.tan(nuf / 2))
M0 = e * np.sinh(F0) - F0
Mf = e * np.sinh(Ff) - Ff
n = np.sqrt(398600.0 / -a ** 3) # the mean motion
deltat = (Mf - M0) / n # change of time in secs
hours = deltat / 3600
h = np.sqrt(a * 398600 * (1 - e ** 2))
def r(nu):
return h ** 2 / (398600 * (1 + e * np.cos(nu)))
rt = r(nu)
ext = [np.argmin(rt), np.argmax(rt)]
rt[ext] = np.nan
nu = np.linspace(0, 2 * np.pi, 500000)
fig = pylab.figure()
ax = fig.add_subplot(111, aspect = 'equal')
earth = pylab.Circle((0, 0), radius = 6378, color = 'blue')
ax.add_patch(earth)
ax.plot(rt * np.cos(nu), rt * np.sin(nu), 'r')
pylab.axis([-70000, 10000, -40000, 40000])
pylab.show()
How can I find the closet distance between my trajectory and (384400,0,0)?
Also, how can I the distance from (384400,0,0) to the path at time t = 197465?
I understand that the arrays have the data but is there a way to have it check the distance of all the points (x,y,z) and return what I am looking for?
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
me = 5.974 * 10 ** (24) # mass of the earth
mm = 7.348 * 10 ** (22) # mass of the moon
G = 6.67259 * 10 ** (-20) # gravitational parameter
re = 6378.0 # radius of the earth in km
rm = 1737.0 # radius of the moon in km
r12 = 384400.0 # distance between the CoM of the earth and moon
M = me + mm
pi1 = me / M
pi2 = mm / M
mue = 398600.0 # gravitational parameter of earth km^3/sec^2
mum = G * mm # grav param of the moon
mu = mue + mum
omega = np.sqrt(mu / r12 ** 3)
nu = -129.21 * np.pi / 180 # true anomaly angle in radian
x = 327156.0 - 4671
# x location where the moon's SOI effects the spacecraft with the offset of the
# Earth not being at (0,0) in the Earth-Moon system
y = 33050.0 # y location
vbo = 10.85 # velocity at burnout
gamma = 0 * np.pi / 180 # angle in radians of the flight path
vx = vbo * (np.sin(gamma) * np.cos(nu) - np.cos(gamma) * np.sin(nu))
# velocity of the bo in the x direction
vy = vbo * (np.sin(gamma) * np.sin(nu) + np.cos(gamma) * np.cos(nu))
# velocity of the bo in the y direction
xrel = (re + 300.0) * np.cos(nu) - pi2 * r12
# spacecraft x location relative to the earth
yrel = (re + 300.0) * np.sin(nu)
# r0 = [xrel, yrel, 0]
# v0 = [vx, vy, 0]
u0 = [xrel, yrel, 0, vx, vy, 0]
def deriv(u, dt):
n1 = -((mue * (u[0] + pi2 * r12) / np.sqrt((u[0] + pi2 * r12) ** 2
+ u[1] ** 2) ** 3)
- (mum * (u[0] - pi1 * r12) / np.sqrt((u[0] - pi1 * r12) ** 2
+ u[1] ** 2) ** 3))
n2 = -((mue * u[1] / np.sqrt((u[0] + pi2 * r12) ** 2 + u[1] ** 2) ** 3)
- (mum * u[1] / np.sqrt((u[0] - pi1 * r12) ** 2 + u[1] ** 2) ** 3))
return [u[3], # dotu[0] = u[3]
u[4], # dotu[1] = u[4]
u[5], # dotu[2] = u[5]
2 * omega * u[5] + omega ** 2 * u[0] + n1, # dotu[3] = that
omega ** 2 * u[1] - 2 * omega * u[4] + n2, # dotu[4] = that
0] # dotu[5] = 0
dt = np.arange(0.0, 320000.0, 1) # 200000 secs to run the simulation
u = odeint(deriv, u0, dt)
x, y, z, x2, y2, z2 = u.T
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z)
plt.show()
To find the distance along each point in the trajectory:
my_x, my_y, my_z = (384400,0,0)
delta_x = x - my_x
delta_y = y - my_y
delta_z = z - my_z
distance = np.sqrt(np.power(delta_x, 2) +
np.power(delta_y, 2) +
np.power(delta_z, 2))
And then to find the min and that specific distance:
i = np.argmin(distance)
t_min = i / UNITS_SCALE # I can't tell how many units to a second. Is it 1.6?
d_197465 = distance[int(197465 * UNITS_SCALE)]
PS, I'm no rocket scientist, and thus haven't actually checked the stuff above x, y, z, x2, y2, z2 = u.T. I'm assuming that those are your trajectory's position and velocity?