Related
I got the error mentioned before in the line 51 of the following code:
import csv
import math
from datetime import datetime
with open('BBDD1') as csv_file:
csv_reader1 = csv.reader(csv_file, delimiter=',')
with open('BBDD2') as csv_file:
csv_reader2 = csv.reader(csv_file, delimiter=',')
contador1=0
contador2=0
cont=0
bbdd1=[]
bbdd2=[]
d=float(input("Ingrese la distancia en metros entre el evento sísmico y la tronadura: "))
for fila1 in csv_reader1:
if fila1 != []:
bbdd1.append(fila1)
for fila2 in csv_reader2:
if fila2 != []:
bbdd2.append(fila2)
#for i in range(50):
#print(i)
#print(len(bbdd1))
#print(float(bbdd1[3][6].replace(",",".")))
i=0
for i in range(len(bbdd1)):
for j in range(len(bbdd2)):
#print(bbdd1[fila1][fila2])
#print(bbdd1[fila1][6])
#print(fila1)
cont+=1
print(i)
print(j)
distancia=((float(bbdd1[i+1][6].replace(",","."))-float(bbdd2[j+1][3]))**2 + (float(bbdd1[i+1][7].replace(",","."))-float(bbdd2[j+1][4]))**2 + (float(bbdd1[i+1][8].replace(",","."))-float(bbdd2[j+1][5]))**2)**0.5
if distancia <d:
print("La distancia es: ", distancia)
print("El evento " + str(bbdd2[j+1][0]) + " está relacionado con la tronadura " + str(bbdd1[i+1][0]))
print("Los números de eventos sísmicos relacionados a las tronaduras con una distancia entre ambas de " + str(d) + " m es de " + str(cont))
I was trying to relation the following 2 database:
bbdd1:
N° Quemada,Fecha,Hora,PK,Avance,Acumulado,Norte,Este,Corte,Fecha y hora,Date time
1,24-09-2019,TB 08:04,"7309,12","3,82","3,82","-468,965","-563,220","1671,935",24-09-2019 08:04,2019-09-24 08:04:00
2,06-10-2019,TA 16:41,"7311,48","2,36","6,18","-467,728","-561,210","1676,133",06-10-2019 16:41,2019-10-06 16:41:00
.
.
.
bbdd2:
Index,Event Date,EventTimeInDay,LocX [m],LocY [m],LocZ [m],Local Magnitude,Log Potency [log m^3],Log Energy [log J],Log(EnergyS/EnergyP),TriggerCount,Fecha y hora,Date time
1,2021/02/16,21:35:03,-502.5,-415.0,1660.8,-1.0,-2.88,-0.61,1.80,8,2021/02/16 21:35:03,2021-02-16 21:35:03
2,2021/03/14,01:20:59,-478.6,-414.9,1690.9,-1.3,-3.37,0.34,1.28,6,2021/03/14 01:20:59,2021-03-14 01:20:59
.
.
.
(There are many more rows, 56 rows in bbdd1 and 3447 rows in bbdd2). The problem is the double "for" because the "i" variable of the first "for" never changes, it gets stuck in i=0 and it should change to i=56 from i=0 with steps of 1.
I have downloaded multiple tiles from OpenStreetMaps, and I need to join all the tiles to form a single image, the truth is I am quite new to this topic and I do not know a lot.
Until now I made a small script to join the tiles, the objective is to join the tiles so that they coincide with each other, so that they form an image of the map region ... with the script I managed to join the tiles but not the problem is that they do not match.
I share my script and I would appreciate any help you can give me.
This is my scritp:
import numpy as np
from PIL import Image
import glob
def join_images_horizontally(imgs):
'''
Esta función une imagenes horizontalmente.
'''
#crea dos listas: una para alturas y otra para anchuras
widths, heights = zip(*(i.size for i in imgs))
width_of_new_image = sum(widths)
height_of_new_image = min(heights) #toma la altura minima
# crear nueva imagen
new_im = Image.new('RGB', (width_of_new_image, height_of_new_image))
new_pos = 0
for im in imgs:
new_im.paste(im, (new_pos,0))
new_pos += im.size[0] #position for the next image
new_im.save('/home/orlando/git/orlando3dmaps/src/imghorizontal.png')
def join_images_vertically(imgs):
'''
Esta función une imagenes verticalmente.
'''
#crea dos listas: una para alturas y otra para anchuras
widths, heights = zip(*(i.size for i in imgs))
width_of_new_image = min(widths) #toma la altura minima
height_of_new_image = sum(heights)
# ccrear nueva imagen
new_im = Image.new('RGB',(width_of_new_image, height_of_new_image))
new_pos = 0
for im in imgs:
new_im.paste(im, (0, new_pos))
new_pos += im.size[1] #posicion para la siguiente imagen
new_im.save('/home/orlando/git/orlando3dmaps/src/imgvertical.png')
def main():
'''
Inicializa el código.
'''
# Abrir archivos de imagen
imgs = [Image.open(im) for im in list_im]
###fusionar imagenes horizontalmente
#join_images_horizontally(imgs)
###fusionar imagenes verticalmente
join_images_vertically(imgs)
#lista de imagenes
list_im = glob.glob("/home/orlando/git/orlando3dmaps/src/tiles/11/494/*.png") #change it to use your images
if __name__ == '__main__':
'''
Este programa fusiona imagenes vertical y horizontalmente.
'''
main()
This generates an output like the following image:
enter image description here
The way to join is fine, but the problem as I said is that they are not in the correct order, they do not match the map.
This is how it should look:enter image description here
Thank you in advance for your help.
I'm trying to implement an artificial neural network that I just trained using this code.
import numpy as np
import os
training_path = 'Imagenes/train'
training_names = os.listdir(training_path)
image_paths = []
image_classes = []
class_id = 0
def imglist(path):
return [os.path.join(path,f) for f in os.listdir(path)]
for training_name in training_names:
dir = os.path.join(training_path, training_name)
class_path = imglist(dir)
image_paths += class_path
image_classes += [class_id]*len(class_path)
class_id+=1
des_list = []
sift = cv2.xfeatures2d.SIFT_create(100)
for image_path in image_paths:
im = cv2.imread(image_path, 0)
kp, des = sift.detectAndCompute(im, None)
des_list.append((image_path, des))
descriptors = des_list[0][1]
for image_path, descriptor in des_list[1:]:
descriptors = np.vstack((descriptors,descriptor))
descriptors_float = descriptors.astype(float)
from scipy.cluster.vq import kmeans, vq
k = 1000
voc, variance = kmeans(descriptors_float, k, 1)
im_features = np.zeros((len(image_paths), k), "float32")
for i in range(len(image_paths)):
words, distance = vq(des_list[i][1], voc)
for w in words:
im_features[i][w] += 1
nbr_ocurrences = np.sum((im_features > 0) * 1, axis = 0)
idf = np.array(np.log((1.0*len(image_paths)+1) / (1.0*nbr_ocurrences + 1)), 'float32')
from sklearn.preprocessing import StandardScaler
stdSlr = StandardScaler().fit(im_features)
im_features = stdSlr.transform(im_features)
print(np.shape(im_features))
print(np.shape(image_classes))
from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(hidden_layer_sizes=(50,50), max_iter=5000, alpha=0.001,
solver='sgd', verbose=10, random_state=21,tol=0.000000001)
clf.fit(im_features, np.array(image_classes))
from sklearn.externals import joblib
joblib.dump((clf, training_names, stdSlr, k, voc), 'sift.pkl', compress = 3)
Well basically that's it and what I'm trying to implement is this
import cv2
import numpy as np
from sklearn.externals import joblib
#Cargando parámetros del modelo, clases y desviaciones estandar par normalizar, además de los clusters
clf, class_names, stdSlr, k, voc = joblib.load('sift.pkl')
#Creando SIFT
sift = cv2.xfeatures2d.SIFT_create(100)
#Objeto de video
video = cv2.VideoCapture('video2.mp4')
fgbg = cv2.createBackgroundSubtractorMOG2()
#Ciclo infinito
while True:
#Leer siguiente cuadro
ret, frame = video.read()
#Si hay siguiente cuadro, ret es TRUE de lo contrario es false y se rompe el ciclo
if ret:
porcentaje_escala = 100 # percent of original size
width = int(frame.shape[1] * porcentaje_escala / 100)
height = int(frame.shape[0] * porcentaje_escala / 100)
dim = (width, height)
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
#Mostramos el cuadro leído
cv2.imshow('Video Original', frame)
#Convertimos el cuadro a escala de grises para procesarlo
frame_gris = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('Escala de Grises',frame_gris)
#Aplicamos MOG acá
fgmask = fgbg.apply(frame_gris)
#Le hacemos thresholding para eliminar las sombras que el MOG2 deja en gris
ret,fgmask = cv2.threshold(fgmask,250,255,cv2.THRESH_BINARY)
#Aplicamos un pequeño filtro para quitarle ruido a la máscara
fgmask = cv2.GaussianBlur(fgmask,(3,3),0)
#Ahora vamos a dilatar y erosionar un poco la máscara para poder darle un espacio blanco al objeto
#no que detecte la forma sino sólo su espacio
kernel = np.ones((8,8),np.uint8)
fgmask = cv2.dilate(fgmask,kernel,iterations = 1)
fgmask = cv2.erode(fgmask,kernel,iterations = 1)
cv2.imshow('Mascara de MOG2',fgmask)
#Ahora hacemos el AND bit a bit de la máscara y la imagen original
res = cv2.bitwise_and(frame,frame,mask = fgmask)
cv2.imshow('resultado',res)
#Hallamos los componentes que comparten bits blancos en la imagen
contours, hierarchy = cv2.findContours(fgmask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[-2:]
#Se dibuja cada contorno si su alto y ancho es mayor a 20 pixeles
ROI=[]
for c in contours:
x,y,w,h = cv2.boundingRect(c)
if((w>20) and (h>20)):
ROI.append(frame[x:x+w,y:y+h])
ROI_Valida=[]
for i in range(len(ROI)):
if(np.shape(ROI[i])[0] > 0):
ROI_Valida.append(ROI[i])
for i in range(len(ROI_Valida)):
kp, des = sift.detectAndCompute(ROI_Valida[i], None)
test_features = np.zeros(k, "float32")
from scipy.cluster.vq import vq
words, distance = vq(des, voc)
for w in words:
test_features[w] += 1
Mostramos la imagen final
if cv2.waitKey(1) & 0xFF == ord('q'):
break;
else:
break;
However in this line in the implementation
words, distance = vq(des, voc)
I'm getting the next error
Traceback (most recent call last):File "C:\Universidad\Trabajo de Grado\Pruebas\p2.py", line 60, in words, distance = vq(des, voc)
File "C:\Python36\lib\site-packages\scipy\cluster\vq.py", line 201, in vq obs = _asarray_validated(obs, check_finite=check_finite)
File "C:\Python36\lib\site-packages\scipy_lib_util.py", line 249, in _asarray_validated raise ValueError('object arrays are not supported')
ValueError: object arrays are not supported
Which doesn't make sense to me as it's the same line used in training with a set of matrix.
I'd appreciate any help.
I want to open a file to edit what's inside with but i get this error
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/LittleSmashBros/Editeur de niveau.py", line 95, in <module>
fichier = open("niveau1.txt",)
TypeError: Required argument 'flags' (pos 2) not found
This is not my first time coding something but I am pretty new to this. My textfile is in the right file, it worked before. It stopped working when I added the function fichier_temp. If you could find what's the problem and explain how to solve it. This is my code, sorry for the variable name, I am French.
from tkinter import *
from os import *
fenetre = Tk()
fenetre.title("LittleSmashBros")
fenetre.geometry("1110x720")
bgImage = PhotoImage(file="Greenbg.png")
fond = Canvas(fenetre,width=1110,height=720)
fond.place(x=-2,y=-2)
fond.create_image(0,0,image=bgImage,anchor="nw")
fond.create_rectangle(1080,0,1111,720,fill="black")
#Stocke les images dans des variables
platGauche = PhotoImage(file="platGauche.png")
platMilieu = PhotoImage(file="platMilieu.png")
platDroite = PhotoImage(file="platDroite.png")
#Bouton qui définissent le bloc choisi
typeBloc = "V"
couleurB = "black"
def changeBloc(bloc): typeBloc = bloc
def boutonEnfonce(bouton) :
bloc1.config(bg=couleurB)
bloc2.config(bg=couleurB)
bloc3.config(bg=couleurB)
bouton.config(bg="white")
bloc1 = Button(fenetre,image=platGauche,height=21,width=21,relief=FLAT,bg=couleurB,command=lambda : [changeBloc("G"),boutonEnfonce(bloc1)])
bloc2 = Button(fenetre,image=platMilieu,height=21,width=21,relief=FLAT,bg=couleurB,command=lambda : [changeBloc("M"),boutonEnfonce(bloc2)])
bloc3 = Button(fenetre,image=platDroite,height=21,width=21,relief=FLAT,bg=couleurB,command=lambda : [changeBloc("D"),boutonEnfonce(bloc3)])
bloc1.place(x=1082,y=10)
bloc2.place(x=1082,y=41)
bloc3.place(x=1082,y=72)
#Prend les coordonnées de la souris et donne sa position sur la grille
def cordsouris(cord):
global x0,y0
x0 = cord.x
y0 = cord.y
x1 = 0
x2 = 22
y1 = 0
y2 = 22
testx = False
testy = False
colonne = 0
ligne = 0
while testx == False:
if x1 < x0 < x2:
testx = True
colonne = colonne + 1
else:
colonne = colonne + 1
x1 = x1+21
x2 = x2+21
print(colonne)
while testy == False:
if y1 < y0 < y2:
testy = True
ligne = ligne + 1
else:
ligne = ligne + 1
y1 = y1+21
y2 = y2+21
print(ligne)
return (colonne,ligne)
#Créé la ligne a remplacer
def remplace_str_index(ligne,place,remplacement):
texte = fichier.readline(ligne)
return '%s%s%s'%(texte[:place],remplacement,texte[place+1:])
#Copie l'ancien fichier dans un nouveau avec la modification
def fichier_temp():
fichier = open("niveau1.txt")
colonne,ligne = cordsouris()
with open("temp.txt","w")as temp:
nb = 0
for rang in fichier:
nb = nb+1
if nb==ligne: text = remplace_str_index(ligne,colonne-1,typeBloc)
else : text = rang
temp.write(text)
print(rang)
print(text)
fichier.close()
os.remove("niveau1.txt")
os.rename("temp.txt","niveau1.txt")
#Détecte le click et effectue le changement de bloc
fond.bind("<Button 1>",fichier_temp)
#Place l'image en fonction du fichier texte
fichier = open("niveau1.txt",)
x=0
y=0
for rang in fichier:
for caractere in rang:
if caractere=="S":
fond.delete(fond.find_closest(x,y))
if caractere=="G":
fond.create_image(x,y,image=platGauche,anchor="nw")
if caractere=="M":
fond.create_image(x,y,image=platMilieu,anchor="nw")
if caractere=="D":
fond.create_image(x,y,image=platDroite,anchor="nw")
x = x+21
x = 0
y = y+21
fichier.close()
fenetre.mainloop()
This is exactly why you should never use from X import *.
from os import * overridden the builtin open in Python with os.open (which, unlike the builtin open, does not have a mode).
Either remove the star import or provide a flag like you have in the other places you used os.open.
You need to provide the file open mode
open("niveau1.txt", "r")
This is the problem:
from os import *
It also imports os.open which now overrides the builting open.
If you only import the parts you need from os it will work fine.
Hi I am trying to calculate the implied vol but because my variable T is under 0.1 I am getting this strange error. "divide by zero encountered in double_scalars"
I would like to know what I am doing wrong. Thanks.
#Importamos librerias
from math import log,exp,sqrt
from scipy import stats
#Definimos nuestra funcion acumulativa
N = stats.norm.cdf
#Definimos la formula de Black Scholes para una opción Call
def BS(S0,K,T,r,sigma):
S0 = float(S0)
d1 = (log(S0/K)+(r + 0.5 * sigma**2)*T)/(sigma*sqrt(T))
d2 = (log(S0/K)+(r - 0.5*sigma**2)*T)/(sigma*sqrt(T))
value = (S0*N(d1)-K*exp(-r*T)*N(d2))
return value
#Definimos Vega que es la derivada con respecto de sigma
def Vega(S0,K,T,r,sigma):
S0 = float(S0)
d1 = (log(S0/K)+(r + 0.5 * sigma**2)*T)/(sigma*sqrt(T))
vega = S0 * N(d1)*sqrt(T)
return vega
#Definimos la volatilidad implicita usando BS y Vega, usamos el metodo de
#Newton para resolver
def ImpliedVol(S0, K, T, r, C0, sigma_est, it=100):
for i in range(it):
sigma_est -= ((BS(S0,K,T,r, sigma_est)-C0)/Vega(S0,K,T,r,sigma_est))
return sigma_est
#Calculamos de Acuerdo a los parametros
S0 = 173
K = 130
T = 0.02
r = 0.029
C0 = 42
Sigma_init = 0.5
print(ImpliedVol(S0,K,T,r,C0,Sigma_init))