Annotating images from h5 file - python

.Hi all, I have 70k images saved into .h5 file and now with this script I want to read from that file and annotate text instances into .json file. When I run this script it takes very long time to annotate 1 image (cca 2h).
When I do this with 15 images then the script works fine and annotate all 15 images about a few seconds.
Now with 70k images -> .h5 file is 51gb.
I don't know is problem in code or the h5 file is too big? Because code works fine with small amount of images, but I'm working on some project where I need 70k or 700k images.
from __future__ import division
import os
import os.path as osp
from re import U
import numpy as np
import matplotlib.pyplot as plt
import h5py
from common import *
import json
import cv2
import numpy as np
from itertools import cycle
import js2py
#from gen import brojac
#from synthgen import imnames
global x
global y
def write_json(data, filename='annotation.json'):
with open(filename,'w') as file:
json.dump(data,file,indent=4)
DATA_PATH = 'results'
DB_FNAME = osp.join(DATA_PATH,'SynthText.h5')
def get_data():
return h5py.File(DB_FNAME,'r')
def viz_textbb(text_im, imageName, charBB_list, wordBB, textToList, alpha=1.0):
"""
text_im : image containing text
charBB_list : list of 2x4xn_i bounding-box matrices
wordBB : 2x4xm matrix of word coordinates
"""
#print("k",z, type(z))
plt.close(1)
plt.figure(1)
plt.imshow(text_im)
H,W = text_im.shape[:2]
global imnames
#print("MOLIIIM",wordBB)
#DODANO IZ MAIN-a
#**********************************************
db = h5py.File('results/SynthText.h5', 'r')
dsets = sorted(db['data'].keys())
for k in dsets:
db = get_data()
imnames = sorted(db['data'].keys())
start = 0
count = 0
coordinate = []
coordinate1 = []
name = []
name1 = []
final = []
upperList = []
downList = []
counter = 0
FinalFinal = []
imageData = { }
dictList = []
for eachWord in textToList:
length = len(eachWord)
for i in range(0,4):
for j in range(start,length+start):
coordinate.append([charBB_list[0][0][i][j], charBB_list[0][1][i][j]])
coordinate1.append((charBB_list[0][0][i][j], charBB_list[0][1][i][j]))
name.append(coordinate)
name1.append(coordinate1)
coordinate = []
for j in range(0, length):
for i in range(len(name)) :
#print(i,j, name[i][j]) ## koordinate da se snađem, treba
final.append(name[i][j])
#print(name)
#NEŠTA ZA CRTANJE, NEBITNO
if(i == 0 or i == 1):
upperList.append(name[i][j])
if(i == 2):
downList.append(name[i+1][j])
if(i == 3):
downList.append(name[i-1][j])
down = reversed(downList)
joinList = [*upperList,*down,upperList[0]]
FinalFinal.append(joinList)
imageData['transcription']=eachWord
imageData['language']="Latin"
imageData['illegibility']=False
imageData['points']=final
dictionary_copy = imageData.copy()
dictList.append(dictionary_copy)
del(dictionary_copy)
finalToList = np.array(final)
name=[]
final = []
upperList = []
downList = []
start = len(eachWord) + start
#del(dictList[0])
finalDict = {f'gt_{imageName}':dictList}
#print(type(finalDict)) --> dict
#print(imageName,finalDict)
#print(finalDict)
#print(len(textToList))
#print(textToList)
with open("annotation.json") as json_file:
data=json.load(json_file)
temp=data["annotations"]
#temp.append(finalDict)
temp.update(finalDict)
#temp['annotations'] = finalDict
write_json(data)
json_file.close()
for list in FinalFinal:
x,y = zip(*list)
plt.plot(x,y)
#print(x,y)
# points = tuple(zip(x,y))
# # boundaries of the bounding box
# left, right = min(points, key=lambda p: p[0]), max(points, key=lambda p: p[0])
# bottom, top = min(points, key=lambda p: p[1]), max(points, key=lambda p: p[1])
# # area
# base = right[0] - left[0]
# height = top[1] - bottom[1]
# A = base * height
#print(A)
for i in range(len(charBB_list)):
# #print(charBB_list) #ispisuje x-eve za jedan vrh svih instanci pojedinih slova, pa drugi, 3. i 4. i onda posebno y-one
bbs = charBB_list[i]
ni = bbs.shape[-1]
for j in range(ni):
bb = bbs[:,:,j]
bb = np.c_[bb,bb[:,0]] #ako se doda ,bb[:,0] -> printa isto kao i gornji lijevi
#plt.plot(bb[0,:], bb[1,:], 'r', alpha=alpha)
# plot the word-BB:
for i in range(wordBB.shape[-1]):
bb = wordBB[:,:,i] #koordinate wordBB-a
bb = np.c_[bb,bb[:,0]] #spaja skroz lijevu, TREBA
#plt.plot(bb[0,:], bb[1,:], 'g', alpha=alpha)
# visualize the indiv vertices:
vcol = ['r','g','b','k']
#for j in range(4):
#plt.scatter(bb[0,j],bb[1,j],color=vcol[j])
#print(bb) # ----> KOORDINATE wordBB-a
#print(bb[1,j])
plt.gca().set_xlim([0,W-1])
plt.gca().set_ylim([H-1,0])
plt.show(block=False)
def main(db_fname):
db = h5py.File(db_fname, 'r')
dsets = sorted(db['data'].keys())
print ("total number of images : ", colorize(Color.RED, len(dsets), highlight=True))
for k in dsets:
rgb = db['data'][k][...]
charBB = db['data'][k].attrs['charBB']
wordBB = db['data'][k].attrs['wordBB']
txt = db['data'][k].attrs['txt']
textToList = (db['data'][k].attrs['txt']).tolist()
#print(textToList)
viz_textbb(rgb, k,[charBB], wordBB, textToList)
print ("image name : ", colorize(Color.RED, k, bold=True))
print (" ** no. of chars : ", colorize(Color.YELLOW, charBB.shape[-1]))
print (" ** no. of words : ", colorize(Color.YELLOW, wordBB.shape[-1]))
print (" ** text : ", colorize(Color.GREEN, txt))
#print("To know", z[1], type(z[1]))
# OTKOMATI OVO DOLJE AKO ŽELIM STISKAT ENTER
# if 'q' in input("next? ('q' to exit) : "):
# break
db.close()
if __name__=='__main__':
main('results/SynthText.h5')

Related

Data from three .txt files - loop together to one, and make a plot?

I want to end up with a scatterplot that differentiates color between different values.
First i need to analyze my data. Problem is i have a FE-Model, that exports element numbers coupled with 4 nodes. These 4 nodes have 4 coordinate sets, but if 4 elements share 1 node, it will only give 1 coordinate set for these 4 nodes.
I end up with three .txt files.
.txt with element number (and data i am analyzing for the plot)
.txt with the element number and node numbers.
.txt with node coordinates.
Is it possible to make a loop that connects these datapoints?
I would like to include an example, but i have not yet made one.
I have tried something like this
from numpy import loadtxt
from fpdf import FPDF
Sek = ['Sektion_100']
I = 0
HeaderY =['nr.','LC','Element nr.','Myy','Nyy','MRd_y','URy']
HeaderX =['nr.','LC','Element nr.','Mxx','Nxx','MRd_x','URx']
#load the excel file
#header = loadtxt"Loads\Area_233.txt", unpack=False, skiprows=1)
pdf = FPDF(orientation = 'P', unit = 'mm', format = 'A4')
MaxURx =[]
MaxURy =[]
data = loadtxt("Loads/Sektion_150.txt", unpack=False, skiprows=1)
nr = data[:,1]
Mxx = data[:,2]
Nxx = -data[:,4]
Myy = data[:,3]
Nyy = -data[:,5]
topologi = loadtxt("Loads/Sektion_150_topologi.txt", unpack=False, skiprows=1)
nr1 = topologi[:,0]
node1 = topologi[:,1]
node2 = topologi[:,2]
node3 = topologi[:,3]
node4 = topologi[:,4]
knuder = loadtxt("Loads/Sektion_150_knuder.txt", unpack=False, skiprows=1)
nr2 = knuder[:,0]
x = knuder[:,1]
y = knuder[:,2]
z = knuder[:,3]
Picture of dataset
I have included a picture of my dataset here. In "Sektion_150_Knuder" NR = Node number.
I hope anyone have some pointers in the right direction to solve this problem.
I found the answer.
import xlwings as xw
import matplotlib.pyplot as plt
from math import pi
from numpy import loadtxt
import numpy as np
from fpdf import FPDF
import matplotlib as mpl
from matplotlib.ticker import ScalarFormatter
Sek = ['Sektion_100','Sektion_110','Sektion_120','Sektion_130','Sektion_140','Sektion_150']
I = 0
HeaderY =['nr.','LC','Element nr.','Myy','Nyy','MRd_y','URy']
HeaderX =['nr.','LC','Element nr.','Mxx','Nxx','MRd_x','URx']
#load the excel file
#header = loadtxt"Loads\Area_233.txt", unpack=False, skiprows=1)
pdf = FPDF(orientation = 'P', unit = 'mm', format = 'A4')
MaxURx =[]
MaxURy =[]
Elem = np.array(loadtxt("Element/Sektion_100_elements.txt", unpack=False, skiprows=1))
Node = np.array(loadtxt("Element/Sektion_100_nodes.txt", unpack=False, skiprows=1))
#Elem = np.array(loadtxt("Element/"+Sek+"_elements.txt", unpack=False, skiprows=1))
#Node = np.array(loadtxt("Element/"+Sek+"_nodes.txt", unpack=False, skiprows=1))
data = loadtxt("Loads/Sektion_100.txt", unpack=False, skiprows=1)
Mxx = data[:,2]
Nxx = -data[:,4]
Myy = data[:,3]
Nyy = -data[:,5]
R1x = []
R2x = []
MRdx = []
URx = []
R1y = []
R2y = []
MRdy = []
URy = []
min_nx = int(round(max(min(Nxx),-300),-1)-10)
max_nx = int(round(max(Nxx),-1)+10)
min_ny = int(round(min(Nyy),-1)-10)
max_ny = int(round(max(Nyy),-1)+10)
xrange = range(min_nx, max_nx+50, round((max_nx+50-min_nx)/20))
yrange = range(min_ny, max_ny+50, round((max_ny+50-min_ny)/20))
x2 =range(0,len(data),1)
wbx =xw.Book("Capacity\\Sektion_100_L.xlsm", None, True)
sht_x1 = wbx.sheets["Beregning"]
for i in xrange:
kx = sht_x1.range("N25").value = i
Q1x = sht_x1["AV24"].value
Q2x = sht_x1["BC24"].value
R1x+=[Q1x]
R2x+=[Q2x]
for i in x2:
if Myy[i] <= 0:
mrdx = np.interp(Nxx[i],xrange,R1x)
urx = Mxx[i] / mrdx
else:
mrdx = np.interp(Nxx[i],xrange,R2x)
urx = Mxx[i] / mrdx
MRdx += [round(mrdx,2)]
URx += [round(urx,2)]
TabelX=np.c_[data[:,[0,1,2,4]],MRdx,URx]
sort_tabelX = np.flipud(TabelX[TabelX[:,5].argsort()])
LimX = 25
for i in x2:
if sort_tabelX[i,5] > 1.05 :
LimX = i+2
else:
break
LimX = max(25,LimX)
TABx=np.c_[list(range(1,LimX+1)),sort_tabelX[0:LimX,:]]
TABx2 = np.unique(TABx[:,2])
print(TABx2)
print(len(TABx2))
#OUE=np.array(TABx2)
#np.savetxt("array1.txt", TABx2)
# %%
NumOUE = len(TABx2)
NumElem = len(Elem)
EleRange = range(0,NumElem)
OUERange = range(0,NumOUE)
EO = np.searchsorted(Elem[:,0], TABx2)
print(EO)
EleCorOx =[]
EleCorOy =[]
EleCorOz =[]
EleCorUx =[]
EleCorUy =[]
EleCorUz =[]
for i in EleRange:
Na = np.searchsorted(Node[:,0],Elem[i,1])
Nb = np.searchsorted(Node[:,0],Elem[i,2])
Nc = np.searchsorted(Node[:,0],Elem[i,3])
Nd = np.searchsorted(Node[:,0],Elem[i,4])
print(Na,Nb,Nc,Nd)
if i in EO:
EleCorOx += [(Node[Na,1] + Node[Nb,1] + Node[Nc,1] + Node[Nd,1])/4]
EleCorOy += [(Node[Na,2] + Node[Nb,2] + Node[Nc,2] + Node[Nd,2])/4]
EleCorOz += [(Node[Na,3] + Node[Nb,3] + Node[Nc,3] + Node[Nd,3])/4]
else:
EleCorUx += [(Node[Na,1] + Node[Nb,1] + Node[Nc,1] + Node[Nd,1])/4]
EleCorUy += [(Node[Na,2] + Node[Nb,2] + Node[Nc,2] + Node[Nd,2])/4]
EleCorUz += [(Node[Na,3] + Node[Nb,3] + Node[Nc,3] + Node[Nd,3])/4]
fig = plt.figure()
fig.set_size_inches(20,10)
ax = fig.add_subplot(projection='3d')
ax.scatter3D(EleCorUx,EleCorUy,EleCorUz,color = 'Blue')
ax.scatter3D(EleCorOx,EleCorOy,EleCorOz,color = 'red')
ax.set_zlim(0,27000)
plt.show()
This code is for showing Sektion 100. Small changes gives me the plots for 110, 120, 130 and so on.
If anyone can use it.

How to show text variable in the Tkinter window?

I'm working on thermography camera and i making the interface. I face some error that my textvariable won't print in the tkinter but still can be printed on the shell. What is wrong with my code?
import pandas as pd
import cv2
import matplotlib.pyplot as plt
from tkinter import *
from tkinter.filedialog import askopenfilenames
# List of list
images = []
gs = []
B = []
G = []
R = []
suhu = []
suhuo = []
red = []
green = []
blue = []
waktu = []
utama = Tk()
# Fungsi-fungsi
def mouseRGB(event,x,y,flags,param):
global gambar
if event == cv2.EVENT_LBUTTONDOWN:
colorsB = gambar[y,x,0]
colorsG = gambar[y,x,1]
colorsR = gambar[y,x,2]
R.append(colorsR)
G.append(colorsG)
B.append(colorsB)
def Tutup ():
utama.destroy()
def tolong ():
messagebox.showinfo('Help','Jika terjadi error atau kesulitan dalam menggunakan program ini dapat menghubungi 08111903747')
def loadImages ():
global wkt
global gambar
global tem
wkt = float(wktu.get())
Gambar = askopenfilenames(parent=jwaktu,
title='Select a thermal image file',
filetypes=[('JPG File','*.jpg'),
('PNG File','*.png'),
('All Files','*')])
# Tutorial pake aplikasi
messagebox.showinfo('How to use','After clicking or dragging the selected picture, press S for next image')
# Program olah suhu
# Perintah Load gambar ke python
filenames = Gambar
# Jendela Mouse
cv2.namedWindow('mouseRGB')
cv2.setMouseCallback('mouseRGB',mouseRGB)
time = 0
for file in filenames:
gambar = cv2.imread(file)
time += wkt
cv2.imshow('mouseRGB',gambar)
while(1):
if cv2.waitKey(0) & 0xFF == ord('s') :
for r in R:
red.append(float(r))
for g in G:
green.append(float(g))
for b in B:
blue.append(float(b))
nr = [i * 0.020411398053616 for i in red]
ng = [j * -0.01805397732321 for j in green]
nb = [k * -0.06212844019856 for k in blue]
R.clear()
G.clear()
B.clear()
red.clear()
green.clear()
blue.clear()
lum = nr + ng + nb
lumi = sum(lum)
tem = lumi + 34.9927907296913
if tem >= 33.0 and tem<= 39.0:
suhuo.append(tem)
waktu.append(time)
suhu.append([file,time,tem])
SuhuA = Label(jwaktu,textvariable = tem)
SuhuA.grid(column=1, row = 1)
print(tem)
break
cv2.destroyAllWindows()
# Olah grafik
plt.plot(waktu,suhuo)
plt.xlabel('Waktu (s)')
plt.ylabel('Suhu (C)')
plt.title('Sebaran suhu')
plt.savefig('Sebaran_suhu.png')
plt.show()
# Masukan data kedalam csv
img_df = pd.DataFrame(suhu ,columns = ['Image','Waktu','Temperature'])
img_df.to_csv('Olah_Suhu.csv')
waktu.clear()
suhuo.clear()
def TIP ():
global SuhuA
global wktu
global jwaktu
jwaktu = Tk()
jwaktu.title('Thermal Image Processing')
jwaktu.geometry('600x400')
Tulisanw = Label(jwaktu,text='Enter the sampling time : ')
Tulisanw.grid(column = 0 , row = 0)
wktu = Entry(jwaktu,width = 10)
wktu.grid(column = 1, row = 0)
tombolw = Button(jwaktu,text='Execute',command=loadImages)
tombolw.grid(column = 2, row = 0)
Suhu = Label(jwaktu,text='Temperature Point : ')
Suhu.grid(column = 0, row = 1)
jwaktu.mainloop()
return wktu
# Window GUI
utama.title('TCI - Thermograpgy Camera Interface')
utama.geometry('600x400')
menu = Menu(utama)
program = Menu(menu)
program.add_command(label = 'Close',command=Tutup)
menu.add_cascade(label='File', menu=program)
menu.add_command(label = 'Help',command=tolong)
utama.config(menu=menu)
TombolTIP = Button(utama,width=30,text='Thermal Image Processing',command=TIP)
TombolTIP.grid(padx = 200,pady = 50)
TombolRTM = Button(utama,width=30,text = 'Realtime Thermal Measurment')
TombolRTM.grid(padx=200,pady=150)
utama.mainloop()
When i was executing on the other window the temperature point did not show anything. I have already tried to use 'text' instead of 'textvariable', but nothing happened. Thank you for your help!

How do I get the graph to open a new window when run?

I would like for the resulting graph to be in a new window. I know the phrase, %matplotlib inline puts the graph in the console, but if I remove it it gives me the error
FigureCanvasMac' object has no attribute 'get_renderer.
Is there a way I can go around this?
import re
import ftplib
import os
from urllib.request import urlopen
import json
import matplotlib
%matplotlib inline
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
import numpy as np
import pylab
import re
import sunpy.time
import numpy as np
from numpy.random import *
from matplotlib.patches import Rectangle
from adjustText import adjust_text
import pandas as pd
from scipy import interpolate
import sys
info = []
parsedFilename = []
dateAndTime = []
xcen = []
ycen = []
sciObj = []
xfov = []
yfov = []
matchingAR = []
def getNumberOfEntries(theJSON):
return len(dateAndTime)
def getInfo(counter, theJSON):
cont = True
while cont:
try:
dateAndTime.append(theJSON["Events"][counter]["date"])
xcen.append(float("%.2f" % theJSON["Events"][counter]["xCen"]))
ycen.append(float("%.2f" % theJSON["Events"][counter]["yCen"]))
xfov.append(float("%.2f" % theJSON["Events"][counter]["raster_fovx"]))
yfov.append(float("%.2f" % theJSON["Events"][counter]["raster_fovy"]))
sciObj.append(theJSON["Events"][counter]["sciObjectives"])
counter = counter + 1
getInfo(counter, theJSON)
except IndexError:
cont = False
break
def setXMax(theJSON):
xmax = xcen[0]
for i in range (0, getNumberOfEntries(theJSON)):
if xcen[i] > xmax:
xmax = xcen[i]
return round(xmax + 150,-1)
def setXMin(theJSON):
xmin = xcen[0]
for i in range (0, getNumberOfEntries(theJSON)):
if xcen[i] < xmin:
xmin = xcen[i]
return round(xmin - 150, -1)
def setYMax(theJSON):
ymax = ycen[0]
for i in range (0, getNumberOfEntries(theJSON)):
if ycen[i] > ymax:
ymax = ycen[i]
return round(ymax + 150, -1)
def setYMin(theJSON):
ymin = ycen[0]
for i in range (0, getNumberOfEntries(theJSON)):
if ycen[i] < ymin:
ymin = ycen[i]
return round(ymin - 150, -1)
# def sort():
# for i in range(len(dateAndTime)):
# for j in range(len(xcen)-1, i, -1):
# if ( xcen[j] < xcen[j-1]):
# temp1 = dateAndTime[j]
# dateAndTime[j] = dateAndTime[j-1]
# dateAndTime[j-1] = temp1
# temp2 = xcen[j]
# xcen[j] = xcen[j-1]
# xcen[j-1] = temp2
# temp3 = ycen[j]
# ycen[j] = ycen[j-1]
# ycen[j-1] = temp3
# temp4 = xfov[j]
# xfov[j] = xcen[j-1]
# xfov[j-1]=temp4
# temp5 = yfov[j]
# yfov[j] = ycen[j-1]
# yfov[j-1]=temp5
# temp6 = sciObj[j]
# sciObj[j] = sciObj[j-1]
# sciObj[j-1] = temp6
def sort():
for i in range(len(dateAndTime)):
for j in range(len(dateAndTime)-1, i, -1):
if ( dateAndTime[j] < dateAndTime[j-1]):
temp1 = dateAndTime[j]
dateAndTime[j] = dateAndTime[j-1]
dateAndTime[j-1] = temp1
temp2 = xcen[j]
xcen[j] = xcen[j-1]
xcen[j-1] = temp2
temp3 = ycen[j]
ycen[j] = ycen[j-1]
ycen[j-1] = temp3
temp4 = xfov[j]
xfov[j] = xcen[j-1]
xfov[j-1]=temp4
temp5 = yfov[j]
yfov[j] = ycen[j-1]
yfov[j-1]=temp5
temp6 = sciObj[j]
sciObj[j] = sciObj[j-1]
sciObj[j-1] = temp6
def createAnnotations(theJSON):
annotations = []
for i in range(getNumberOfEntries(theJSON)):
annotations.append('(' + str(xcen[i])+ ', '+ str(ycen[i]) + ')')
return annotations
def fixAnnotations(annotations):
texts = []
for xt, yt, s in zip(xcen, ycen, annotations):
texts.append(plt.text(xt, yt, s))
return texts
def plot(theJSON):
fig, ax = plt.subplots(figsize=(30, 20))
circle = Circle((0, 0), 980, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5)
ax.add_patch(circle)
plt.plot(xcen, ycen, color="red")
plt.plot(xcen, ycen, 'ro', color = 'blue')
plt.xlim([setXMin(theJSON), setXMax(theJSON)])
plt.ylim([setYMin(theJSON), setYMax(theJSON)])
ax.set_xticks(np.arange(setXMin(theJSON), setXMax(theJSON), 50))
ax.set_yticks(np.arange(setYMin(theJSON), setYMax(theJSON), 50))
for i in range(getNumberOfEntries(theJSON)):
if xfov[i] != 0:
xStart = xcen[i] - xfov[i]/20
yStart = ycen[i] - yfov[i]/20
ax.add_patch(Rectangle((xStart, yStart), xfov[i]/10, yfov[i]/10, facecolor='none'))
texts = fixAnnotations(createAnnotations(theJSON))
f = interpolate.interp1d(xcen, ycen)
x = np.linspace(min(xcen), max(ycen), 1000)
y = f(x)
adjust_text(texts, x, y, arrowprops=dict(arrowstyle="->", color='r', lw=2.0), autoalign='y', only_move={'points':'y', 'text':'y'}, expand_points=(1.2, 1.4), force_points=0.40)
plt.grid()
plt.show()
main(False)
def searchOnceMore(searchAgain):
if searchAgain == True:
noaaNmbr = input('Enter desired active region: ')
return noaaNmbr
else:
continueSearch = input('Would you like to search again?(yes/no)')
if continueSearch == 'yes':
noaaNmbr = input('Enter desired active region:')
return noaaNmbr
elif continueSearch == 'no':
sys.exit(0)
else:
print('please enter "yes" or "no"')
searchOnceMore(False)
def main(searchAgain):
noaaNmbr = searchOnceMore(searchAgain)
urlData = "http://www.lmsal.com/hek/hcr?cmd=search-events3&outputformat=json&instrument=IRIS&noaanum="+ noaaNmbr +"&hasData=true"
webUrl = urlopen(urlData)
counter = 0
if (webUrl.getcode()==200):
data = webUrl.read().decode('utf-8')
theJSON = json.loads(data)
getInfo(counter, theJSON)
else:
print ("You done messed up!!!")
sort()
for i in range (getNumberOfEntries(theJSON)):
print(dateAndTime[i])
print("(", xcen[i], ", ", ycen[i], ")")
print(sciObj[i])
print(' ')
if getNumberOfEntries(theJSON) != 0:
plot(theJSON)
else:
print('No observations for active region ' + noaaNmbr)
main()
main(True)
I have also used python and would suggest using John Zelle's graphic file. http://mcsp.wartburg.edu/zelle/python/
It's much more easier to understand and use in my opinion.
To open a new graph window:
Win1 = GraphWin("Graph Window 1", 100,100)
win2 = GraphWin("Graph Window 2", 100,150)
You can also open the python file to understand how it works. It might help understanding how to open a graph window your way. I only know how to open a new Graph Window through this file sorry, I hope it helps anyway!

how to append float numbers to a list in python

I am trying to compare one image with all images of another file , get the difference percentage and print file name of the least difference percentage .... if i try to append the output differences to a list ... i get an error saying " float values cannot be iterated".... this is what i have done so far ....
from itertools import izip
import os
import numpy as np
import cv2
from matplotlib import pyplot as plt
from PIL import Image
import math
res = 0
def take_and_save_picture(im_save):
'''Take a picture and save it
Args:
im_save: filepath where the image should be stored
'''
camera_port = 0
ramp_frames = 30
cap = cv2.VideoCapture(camera_port)
def get_image():
retval, im = cap.read()
return im
for i in xrange(ramp_frames):
temp = get_image()
print("Taking image...")
# Take the actual image we want to keep
camera_capture = get_image()
#im_save_tmp = im_save + '.jpg'
im_save_tmp = im_save
# A nice feature of the imwrite method is that it will automatically choose the
# correct format based on the file extension you provide. Convenient!
cv2.imwrite(im_save_tmp, camera_capture)
# You'll want to release the camera, otherwise you won't be able to create a new
# capture object until your script exits
# del(cap)
img1 = cv2.imread(im_save_tmp, 0)
edges = cv2.Canny(img1, 100, 200)
cv2.imwrite(im_save, edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
def re(path1,path2):
#path1 = raw_input("Enter the path1:")
#path2 = raw_input("Enter the path2:")
i2= Image.open(path2)
listing = os.listdir(path1)
for file in listing:
i1 = Image.open(path1 + file)
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
res = (dif / 255.0 * 100) / ncomponents
print "Difference (percentage):", res
def main():
capture_img = "/Users/Me/Documents/python programs/New/pro.png"
#img_to_compare = "/Users/Me/Documents/python programs/compare/img2.jpg"
take_and_save_picture(capture_img)
path1 = "/Users/Me/Documents/python programs/New/numbers1/"
path2 = "/Users/Me/Documents/python programs/New/pro.png"
re(path1,path2)
if __name__ == '__main__':
main()
the output is the difference
Difference (percentage): 2.52484809028
Difference (percentage): 2.64822048611
Difference (percentage): 2.64822048611
Difference (percentage): 3.55436197917
the values that i get in "res" have to be stored in a list and the minimum value should be found and printed.... please give me some code ... totally new to python ... thank you ...
You're code must be like this:
#######
list_dif = []
def re(path1,path2):
#path1 = raw_input("Enter the path1:")
#path2 = raw_input("Enter the path2:")
i2= Image.open(path2)
listing = os.listdir(path1)
for file in listing:
i1 = Image.open(path1 + file)
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
#######
for n in range(ncomponents):
res = (dif / 255.0 * 100) / (ncomponents + 1)
list_dif.append(res)
print "Difference (percentage):", list_dif
Something like this?
def re(path1,path2):
#path1 = raw_input("Enter the path1:")
#path2 = raw_input("Enter the path2:")
i2= Image.open(path2)
listing = os.listdir(path1)
res = []
for file in listing:
i1 = Image.open(path1 + file)
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
res.append((dif / 255.0 * 100) / ncomponents)
print "Difference (percentage):", res
minimum = min(res) # Find minimum value in res
print(minimum)

mayavi surf() how do I show colorbar?

I can not figure out how to get the colorbar to show. I don't have much experience using mayavi, so I'm not sure what steps I need to to take to be able to figure this out?
Anyone else have similar problems
My code is shown below:
from tkFileDialog import askopenfilename
from StringIO import StringIO
import numpy as np
from mayavi import mlab
#getting the data from a txt file
filename = askopenfilename()
type(filename)
fileAsStr =''
data = []
count= 0
atData=False
with open(filename,'r') as f:
for line in f:
if line.startswith("Note"):
title = line
title = title.strip("Note:")
title = title.strip()
print title
if atData and not line.startswith('Total'): #after the second one begin reading file
line = line.replace(' ','')
#data.append(line)
fileAsStr = fileAsStr + line
if line.startswith('-----'):
count = count +1
if count == 2:
atData = True
dataStrIO = StringIO(fileAsStr)
dataArray = np.loadtxt(dataStrIO, delimiter=',')
dataDim = dataArray.shape
dx = dataArray[0:dataDim[0], 3]
dy = dataArray[0:dataDim[0], 4]
dz = dataArray[0:dataDim[0], 5]
bTotal = dataArray[0:dataDim[0],9]
firstNum = dy[0]
count = 0
while firstNum == dy[count]:
count = count + 1
print 'count=' + str(count)
#arranging the arrays into an acceptable format
from itertools import islice
def solve(lis, n):
it = iter(lis)
return [list(islice(it,n)) for _ in xrange(len(lis)/n)]
dx = np.transpose(solve(dx, count))
dy = np.transpose(solve(dy, count))
dz = solve(dz, count)
bTotal = solve(bTotal, count)
bTotal = np.log10(bTotal)
#making the plot
mlab.options.backend = 'envisage'
surf = mlab.surf(dx,dy, bTotal,warp_scale=2)
mlab.axes(surf, x_axis_visibility= True, y_axis_visibility = True,
z_axis_visibility = True, xlabel='x axis (mm)', ylabel='y axis (mm)',
zlabel ='z axis (mm)', nb_labels=10)
mlab.axes.label_text_property.font_size = 5
mlab.title(title, line_width = .5, height = 1)
mlab.colorbar( title = "magnetic field (Tesla)")
I believe you are missing an mlab.show() command at the end of your script.

Categories