command from terminal input and output will save an assigning directory - python-3.x

In command line, I want to give python hist.py -n 1000 -o /dir and output will be png in the assigning directory. Can anyone help on it?
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import argparse
import os, sys, errno
def plotData(outputDir):
outFilename = "hist.pdf"
outFilepath = os.path.join(outputDir)
parser = argparse.ArgumentParser()
parser.add_argument("-n","--number", help="display a square of a given number",type=int)
parser.add_argument('-o', '--outputDir', required=True,
help='The directory to which plot files should be saved')
args = parser.parse_args()
num=(args.number)
outFilepath=(args.outputDir)
# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
#num=input()
x = mu + sigma * np.random.randn(int(num))
num_bins = 50
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.savefig (outFilepath,outFilename)
plt.show()
plt.close()
I could give random variable but not directory from terminal command line.
I have used args.outputDir but it does not work for me.
and i am learners

Related

ValueError: x and y must have same first dimension, but have shapes (2140699,) and (4281398,)

I use miniconda jupyter notebook python and I'm trying to implement a machine (Audio filtering). I got this error and I really don't know how to fix it.
Here I imported libraries that I need with the path of the file:
import wave as we
import numpy as np
import matplotlib.pyplot as plt
dir = r'/home/pc/Downloads/Bubble audios'
Here the fuction that should plot the graph:
def read_wav(wavfile, plots=True, normal=False):
f = wavfile
params = f.getparams()
# print(params)
nchannels, sampwidth, framerate, nframes = params[:4]
strData = f.readframes(nframes) # , string format
waveData = np.frombuffer(strData, dtype=np.int16) # Convert a string to an int
# wave amplitude normalization
if normal == True:
waveData = waveData*1.0/(max(abs(waveData)))
#
if plots == True:
time = np.arange(0, nframes ,dtype=np.int16) *(1.0 / framerate)
plt.figure(dpi=100)
plt.plot(time, waveData)
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.title("Single channel wavedata")
plt.show()
return (Wave, time)
def fft_wav(waveData, plots=True):
f_array = np.fft.fft(waveData) # Fourier transform, the result is a complex array
f_abs = f_array
axis_f = np.linspace(0, 250, np.int(len(f_array)/2)) # map to 250
# axis_f = np.linspace(0, 250, np.int(len(f_array))) # map to 250
if plots == True:
plt.figure(dpi=100)
plt.plot(axis_f, np.abs(f_abs[0:len(axis_f)]))
# plt.plot(axis_f, np.abs(f_abs))
plt.xlabel("Frequency")
plt.ylabel("Amplitude spectrum")
plt.title("Tile map")
plt.show()
return f_abs
And here I call the function with the file that I want to be read and plotted.
f = we.open(dir+r'/Ars1_Aufnahme.wav', 'rb')
Wave, time = read_wav(f)
The error that I got:
ValueError: x and y must have same first dimension, but have shapes (2140699,) and (4281398,)
I tried to use np.reshape but it didn't work or I might have used it wrong. So, any advice?
it's seems that your time is 1/2 of the size of your wave. Maybe your nframe is too short. If you do nframses = 2*nframes what is the error ?

draw signal spectrum using matplotlib

I have the following signal and I want to do the following:
s= 4*np.cos(4*np.pi*pow(10,6)*t+30)+2*np.sin(8*np.pi*pow(10,6)*t+15)+np.cos(12*np.pi*pow(10,6)*t)+0.5*np.cos(16*np.pi*pow(10,6)*t) # the signal
I want to draw signal spectrum using matplotlib and numpy,
the find its bandwidth and determine if it's periodic or not
I use this code available here(https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/spectrum_demo.html)
thanks for helping
I am not 100% sure if I now what you want to do but it seems plotting and returning all the turning points of your function should help you a lot with your problem.
Therefore you may try this:
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema
def func(t):
# messures the time in units of
# pow(10,6)*t
exp = 4*np.cos(4*np.pi*t+30)+\
2*np.sin(8*np.pi*t+15)+\
np.cos(12*np.pi*t)+\
0.5*np.cos(16*np.pi*t)
return exp
max_time = 2
time_steps = 400
# defining the signal
X = np.linspace(0,max_time,time_steps)
Y = func(X)
# getting all the max and min values
minimas = argrelextrema(Y, np.less)
maximas = argrelextrema(Y, np.greater)
# plot the singal
plt.plot(X,Y)
# plot minimas and maximas
plt.scatter(X[minimas],Y[minimas],color='r')
plt.scatter(X[maximas],Y[maximas],color='g')
plt.xlabel('t*10**6')
plt.ylabel('signal')
plt.show()

Import error: No module named 'mstamp_stomp'

I am trying to run demo.py from the git repository https://github.com/mcyeh/mstamp/tree/master/Python.
This is the source code of the paper Matrix Profile VI: Meaningful Multidimensional Motif Discovery. I have attached the code below.
# -*- coding: utf-8 -*-
"""
#author: Michael Yeh
C.-C. M. Yeh, N. Kavantzas, and E. Keogh, "Matrix Profile VI: Meaningful
Multidimensional Motif Discovery," IEEE ICDM 2017.
https://sites.google.com/view/mstamp/
http://www.cs.ucr.edu/~eamonn/MatrixProfile.html
"""
import scipy.io as sio
import matplotlib.pyplot as plt
from mstamp_stomp import mstamp as mstamp_stomp
from mstamp_stamp import mstamp as mstamp_stamp
def plot_motifs(matrix_profile, dimensionality=1):
motif_at = matrix_profile[dimensionality - 1, :].argsort()[:2]
plt.figure(figsize=(14, 7))
for i in range(3):
plt.subplot(4, 1, i + 1)
plt.plot(data.T[i, :])
plt.title('$T_{}$'.format(i + 1))
for m in motif_at:
plt.plot(range(m, m + sub_len), data.T[i, :][m:m + sub_len], c='r')
plt.xlim((0, matrix_profile.shape[1]))
plt.subplot(414)
plt.title('{}-dimensional Matrix Profile'.format(dimensionality))
plt.plot(matrix_profile[dimensionality - 1, :])
for m in motif_at:
plt.axvline(m, c='r')
plt.xlim((0, matrix_profile.shape[1]))
plt.tight_layout()
if __name__ == '__main__':
mat = sio.loadmat('toy_data.mat')
data = mat['data']
sub_len = mat['sub_len'][0][0]
# using the stomp based method to compute the multidimensional matrix
# profile
mat_pro_1, pro_idx_1 = mstamp_stomp(data.T, sub_len,
return_dimension=False)
# plot the matrix profile as image
plt.figure()
plt.title('Matrix Profile (STOMP)')
plt.imshow(mat_pro_1, extent=[0, 1, 0, 1])
# using the stamp based method to compute the multidimensional matrix
# profile
mat_pro_2, pro_idx_2 = mstamp_stamp(data.T, sub_len,
return_dimension=False)
# plot the matrix profile as image
plt.figure()
plt.title('Matrix Profile (STAMP)')
plt.imshow(mat_pro_2, extent=[0, 1, 0, 1])
plot_motifs(mat_pro_2)
# the function can also be used to compute the 1D matrix profile
mat_pro_3, _ = mstamp_stomp(data[:, 1].T, sub_len,
return_dimension=False)
plt.figure()
plt.plot(mat_pro_3[0, :])
mat_pro_4, _ = mstamp_stamp(data[:, 1].T, sub_len,
return_dimension=False)
plt.figure()
plt.plot(mat_pro_4[0, :])
plt.show()
Import error: No module named 'mstamp_stomp'
This reflects a search path problem. You will want to chdir into the directory containing the sources, and you will also want to have . dot in your path before you execute the code:
$ cd mstamp/Python
$ export PYTHONPATH=.
$ python demo.py
You can use this code fragment to debug such issues:
import pprint
import sys
pprint.pprint(sys.path)

Solving simple ODE using scipy odeint gives straight line at 0

I am trying to solve a simple ODE:
dN/dt = N*(rho(t)-beta)/lambda
Rho is a function of time and I've generated it using linspace. The code is working for other equations but somehow gives a flat straight line at 0. (You can see it in the graph). Any guidelines about how to correct it?
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def model2(N, t, rho):
beta_val = 0.0065
lambda_val = 0.00002
k = (rho - beta_val) / lambda_val
dNdt = k*N
print(rho)
return dNdt
# initial condition
N0 = [0]
# number of time points
n = 200
# time points
t = np.linspace(0,200,n)
rho = np.linspace(6,9,n)
#rho =np.array([6,6.1,6.2,6.3,6.4,6.5,6.6,6.7,6.8,6.9,7.0,7.1,7.2,7.3,7.4,7.5,7.6,7.7,7.8,7.9]) # Array of constants
# store solution
NSol = np.empty_like(t)
# record initial conditions
NSol[0] = N0[0]
# solve ODE
for i in range(1,n):
# span for next time step
tspan = [t[i-1],t[i]]
# solve for next step
N = odeint(model2,N0,tspan,args=(rho[i],))
print(N)
# store solution for plotting
NSol[i] = N[0][0]
# next initial condition
#z0 = N0[0]
# plot results
plt.plot(t,rho,'g:',label='rho(t)')
plt.plot(t,NSol,'b-',label='NSol(t)')
plt.ylabel('values')
plt.xlabel('time')
plt.legend(loc='best')
plt.show()
This is the graph I get after running this code
I modified your code (and the coefficients) to make it work.
When coefficients are also dependent of t, they have to be python functions called by the derivative function:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# Define
def model2(N, t, rho):
beta_val = 0.0065
lambda_val = 0.02
k = ( rho(t) - beta_val )/lambda_val
dNdt = k*N
return dNdt
def rho(t):
return .001 + .003/20*t
# Solve
tspan = np.linspace(0, 20, 10)
N0 = .01
N = odeint(model2, N0 , tspan, args=(rho,))
# Plot
plt.plot(tspan, N, label='NS;ol(t)');
plt.ylabel('N');
plt.xlabel('time'); plt.legend(loc='best');

Counted objects are not accurate in many cases in image proceesing

Before you flag the question please read it first-
I found How to count the number of objects detected with Template Matching?, tutorial and it's good but not perfect.
The problem with this and what I am facing is that, It's not giving accurate counts, but draws the rectangle around all the found(objects) ones!
For example, I have this (Before, executing script):-
Then, I have this (After executing script):-
As you can see clearly, there are 3 rectangles in 4th row but the count it's giving is 1.
I've tried changing threshold and sensitivity, but it didn't work. Here's what I have so far-
# USAGE
===================================================================
# python3 match_template.py --template cod_logo.png --images images
===================================================================
import numpy as np
import argparse
import imutils
import glob
import cv2
from matplotlib import pyplot as plt
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-t", "--template", required=True, help="Path to template image")
ap.add_argument("-i", "--images", required=True,
help="Path to images where template will be matched")
ap.add_argument("-v", "--visualize",
help="Flag indicating whether or not to visualize each iteration")
args = vars(ap.parse_args())
def match_and_count(template, image):
img_rgb = cv2.imread(image)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread(template,0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
f = set()
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
sensitivity = 100
f.add((round(pt[0]/sensitivity), round(pt[1]/sensitivity)))
cv2.imwrite('multiple_objects.jpg',img_rgb)
print("Occurence of Object: %s" % len(f))
match_and_count(args["template"], args["images"])
Does anyone have any better approach of doing the same?

Resources