I have a task where i need to specify the upper left coordinate of the smaller image in the larger image.
I implemented this code, however it is too slow since I have a time limit of 20 seconds, and in some datasets I have 3000 images. How can this be implemented more effectively? I can use numpy, scipy and all packages from the standard python library.
import numpy as np
from PIL import Image
map_image_path = input()
map_image = Image.open(map_image_path)
map_ar = np.asarray(map_image)
map_ar_y, map_ar_x = map_ar.shape[:2]
i = int(input())
dimensions = input()
patches=list()
for k in range(i):
patch_image_path = input()
patches.append(Image.open(patch_image_path))
for j in range(i):
patch_ar = np.asarray(patches[j])
patch_ar_y, patch_ar_x = patch_ar.shape[:2]
stop_x = map_ar_x - patch_ar_x + 1
stop_y = map_ar_y - patch_ar_y + 1
for x in range(0, stop_x):
for y in range(0, stop_y):
x2 = x + patch_ar_x
y2 = y + patch_ar_y
picture = map_ar[y:y2, x:x2]
if np.array_equal(picture, patch_ar):
print(str(x) + "," + str(y))
Related
Hey guys so I am trying to make a Brickwall Frequency Splitter in python 3.+, by this I mean that say I have an audio file, I want to split the audio file into 6 different bands, Sub, Lows, Low-Mids, Mids, High-Mids, Highs. However, I don't want to use a butter filter instead I want a filter that cuts any other frequencies below and above the desired range lets say I want from 200Hz to 400Hz I want a clean cut of them frequencies.
Thanks,
elliott
Currently my code looks like this I have a filter going on but it is like a sweep and doesn't really work for me:
import numpy as np
import sounddevice as sd
import os
import soundfile as sf
import matplotlib.pyplot as plt
sampling_rate = 44100
duration_in_seconds = 30
highpass = False
amplitude = 0.3
duration_in_samples = int(duration_in_seconds *
sampling_rate)
folder_number = 1
folder_number_str = str(folder_number)
folder_type = 'short/'
cut_type = '/30CUT/'
audio_file_dir = os.listdir('for_analysis/' + folder_type + folder_number_str + cut_type)[0]
audio_dir = 'for_analysis/' + folder_type + folder_number_str + cut_type
print(audio_dir)
print(audio_file_dir)
length = len(audio_dir)
file_format = audio_dir[length - 3:]
full_path = audio_dir + audio_file_dir
print(full_path)
data, fs = sf.read(full_path)
print(data.shape, fs)
plt.plot(data)
input_signal = data
cutoff_frequency = np.geomspace(50, 50, input_signal.shape[0])
allpass_output = np.zeros_like(input_signal)
dn_1 = 0
for n in range(input_signal.shape[0]):
break_frequency = cutoff_frequency[n]
tan = np.tan(np.pi * break_frequency / sampling_rate)
a1 = (tan - 1) / (tan + 1)
allpass_output[n] = a1 * input_signal[n] + dn_1
dn_1 = input_signal[n] - a1 * allpass_output[n]
if highpass:
allpass_output *= -1
filter_output = input_signal + allpass_output
filter_output *= 0.5
filter_output *= amplitude
sd.play(filter_output, sampling_rate)
sd.wait()
Unfortutantly, I have searched around the internet to be left with no result. If you have any documentation I could read to help me with this that would be great, or better any code you could show to aid.
Here is my desired result
What I want do do is to ask for a number in the middle of the animation, for in the future be able to animate n circles and be able to change it in the middle of the animation. But when I try asking for an input I get this:
QCoreApplication::exec: The event loop is already running
and the next frame doesn't start until i have given it an input
How do I try getting an input and if not, continue the animation with the past value?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
fig, ax = plt.subplots()
ax.set_xlim(0,100)
ax.set_ylim(0,100)
alphas = [0.5,0.5]
circle = plt.Circle((5, 10), 10, color='b', fill=True, alpha = alphas[0])
circle2 = plt.Circle((5, 10), 5, color='r', fill=True, alpha = alphas[1])
circles = [circle, circle2]
def init():
for i in circles:
i.center = (50,50)
ax.add_patch(i)
return circles
def animation_frame(k):
try:
num = int(input())
except:
pass
finally:
for j in circles:
x,y = j.center
r = random.uniform(-5,5)
r2 = random.uniform(-5,5)
#stop circles from going out
if (((x + j.radius + r) <= 100 ) & ((x - j.radius + r) >= 0 )):
x += r
else:
x -= r
if (((y + j.radius + r2) <= 100 ) & ((y - j.radius + r2) >= 0 )):
y += r2
else:
y -= r2
j.center = (x, y)
return circles
animation = FuncAnimation(fig,animation_frame, init_func=init,frames=360,interval=20,blit=True)
plt.show()
My task is to simulate a 3 DOF robotic arm system in python. The aim is to trace out a 3D Gaussian surface. Input data is coordinates of the end effector gained using 3D Gaussian equation. The code is supposed to solve a system of the trigonometric equation to find out angles theta1, theta2 & theta3. I used "solve([eqn1,eqn2,eqn3],theta1,theta2,theta3)" to solve for the system of equation. Python is taking a too long time to respond.
I tried solving using fsolve, but the results were incomparable to the solution from MATLAB. Btw, I got a very good simulation in MATLAB using "solve".
I am using Python 3.7.3 through spyder under Anaconda 2019.03 environment in Windows 10.
Generating data set (Gaussian surface) : P matrix
a = 8
x0 = 0
y0 = 0
sigmax = 3
sigmay = 3
P_x = np.arange(7,-8,-1)
P_y = np.arange(7,-8,-1)
xx , yy = np.meshgrid(P_x,P_y)
s_x,s_y = np.subtract(xx,x0),np.subtract(yy,y0)
sq_x,sq_y = np.square(s_x),np.square(s_y)
X,Y = np.divide(sq_x,2*(sigmax**2)),np.divide(sq_y,2*(sigmay**2))
E = np.exp(-X-Y)
zz = np.multiply(E,a)
xx,yy,zz = xx.flatten(),yy.flatten(),zz.flatten()
P = np.vstack([yy,xx,zz]).T
import numpy as np
from sympy import *
from sympy import Symbol, solve, Eq
for j in range(len(P)):
theta1 = Symbol('theta1',real = True)
theta2 = Symbol('theta2',real = True)
theta3 = Symbol('theta3',real = True)
x,y,z = P[j,0],P[j,1],P[j,2]
eq1 = Eq(R1*cos(theta1) + R2*cos(theta1)*cos(theta2) +
R3*cos(theta1)*cos(theta3) - x)
eq2 = Eq(R1*sin(theta1) + R2*cos(theta2)*sin(theta1) +
R3*cos(theta3)*sin(theta1) - y)
eq3 = Eq(R2*sin(theta2) + R3*sin(theta3) -z )
solve([eq1,eq2,eq3],theta1,theta2,theta3)
solution[j,0] = degrees(theta1)
solution[j,1] = degrees(theta3)
solution[j,2] = degrees(theta2)
Expected result: Solution matrix with values of theta1, theta2 & theta3.
Python takes too much time to respond.
I am trying to find the values of temperatures between 2250 K to 2300 K and have written a basic equation that uses linear interpolation to define the enthalpies between these temperatures. I am not exactly sure how to do this.
This is the equation:
T1_e = 868739/(0.9*h1_co2 + 0.1*h1_co + 2*h1_h2o + 0.05*h1_o2 + 7.52*h1_n2)
T2_e = 868739/(0.9*h2_co2 + 0.1*h2_co + 2*h2_h2o + 0.05*h2_o2 + 7.52*h2_n2)
The values of h1_co2, h1_co, h2_co2, h2_co and so forth are constants for the respective temperatures of K.
T1_e represents the temperature at 2250 K.
T2_e represents the temperature at 2300 K.
I imagine your answer would something like this
import numpy as np
import matplotlib.pyplot as plt
# define your constants
h1_co2 = 7
h1_co = 12
h2_co2 = 6
h2_co = .5
# etc...
def T1_e(h1_co2, h1_co, h1_h2o, h1_o2, h1_n2):
t1_e = 868739/(0.9*h1_co2 + 0.1*h1_co + 2*h1_h2o + 0.05*h1_o2 + 7.52*h1_n2)
return t1_e
def T2_e(h2_co2, h2_co, h2_h2o, h2_o2, h2_n2):
t2_e = 868739/(0.9*h2_co2 + 0.1*h2_co + 2*h2_h2o + 0.05*h2_o2 + 7.52*h2_n2)
return t2_e
temp = [2250, 2300]
e1 = T1_e(h1_co2, h1_co, h1_h2o, h1_o2, h1_n2)
e2 = T2_e(h2_co2, h2_co, h2_h2o, h2_o2, h2_n2)
e = [e1, e2]
p = np.polyfit(temp, e, 1)
x = np.linspace(2250, 2300, 100)
plt.plot(x, np.poly1d(x))
plt.show()
Instructions: Compute and store R=1000 random values from 0-1 as x. moving_window_average(x, n_neighbors) is pre-loaded into memory from 3a. Compute the moving window average for x for the range of n_neighbors 1-9. Store x as well as each of these averages as consecutive lists in a list called Y.
My solution:
R = 1000
n_neighbors = 9
x = [random.uniform(0,1) for i in range(R)]
Y = [moving_window_average(x, n_neighbors) for n_neighbors in range(1,n_neighbors)]
where moving_window_average(x, n_neighbors) is a function as follows:
def moving_window_average(x, n_neighbors=1):
n = len(x)
width = n_neighbors*2 + 1
x = [x[0]]*n_neighbors + x + [x[-1]]*n_neighbors
# To complete the function,
# return a list of the mean of values from i to i+width for all values i from 0 to n-1.
mean_values=[]
for i in range(1,n+1):
mean_values.append((x[i-1] + x[i] + x[i+1])/width)
return (mean_values)
This gives me an error, Check your usage of Y again. Even though I've tested for a few values, I did not get yet why there is a problem with this exercise. Did I just misunderstand something?
The instruction tells you to compute moving averages for all neighbors ranging from 1 to 9. So the below code should work:
import random
random.seed(1)
R = 1000
x = []
for i in range(R):
num = random.uniform(0,1)
x.append(num)
Y = []
Y.append(x)
for i in range(1,10):
mov_avg = moving_window_average(x, n_neighbors=i)
Y.append(mov_avg)
Actually your moving_window_average(list, n_neighbors) function is not going to work with a n_neighbors bigger than one, I mean, the interpreter won't say a thing, but you're not delivering correctness on what you have been asked.
I suggest you to use something like:
def moving_window_average(x, n_neighbors=1):
n = len(x)
width = n_neighbors*2 + 1
x = [x[0]]*n_neighbors + x + [x[-1]]*n_neighbors
mean_values = []
for i in range(n):
temp = x[i: i+width]
sum_= 0
for elm in temp:
sum_+= elm
mean_values.append(sum_ / width)
return mean_values
My solution for +100XP
import random
random.seed(1)
R=1000
Y = list()
x = [random.uniform(0, 1) for num in range(R)]
for n_neighbors in range(10):
Y.append(moving_window_average(x, n_neighbors))