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!
Related
hi i have a problem where my code is turned into a executable file a error message will appear on the screen does any one know how to fix this error this is for some body tracking software the really cause of this is cv2 but i need some help to make this a executable file so no error messages appeare when opened Many Thanks Jacob PLEASE HELO
[1]: https://i.stack.imgur.com/LKJ5r.png
import cv2
import mediapipe as mp
import pandas as pd
from ast import literal_eval
from tkinter import *
from tkinter import filedialog
import numpy
root = Tk()
#create lebel widget
ScreenLabel = Label(root, text="Body tracking")
#put on screen
root.geometry("500x450+700+200")
#def open():
#global track
#track = filedialog.askopenfilename(initialdir="/dowloads", title="select A File", filetypes=([("all files","*.*")]))
e = Entry(root, width=100)
e.pack()
def tracking():
mp_drawing = mp.solutions.drawing_utils
mp_pose = mp.solutions.pose
video_file_path = e.get()
cap = cv2.VideoCapture(video_file_path)
coordinates_list = []
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
size = (frame_width, frame_height)
fps = 30
v_split = video_file_path.split(".")
v_split[-2] = v_split[-2] + "_processed"
prep_vid_file_path = ".".join(v_split)
video_saver = cv2.VideoWriter(prep_vid_file_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, size)
keypoints_list = ['CENTER_HEAD',
'LEFT_SHOULDER',
'RIGHT_SHOULDER',
'LEFT_ELBOW',
'RIGHT_ELBOW',
'LEFT_WRIST',
'RIGHT_WRIST',
'LEFT_PINKY',
'RIGHT_PINKY',
'LEFT_INDEX',
'RIGHT_INDEX',
'LEFT_THUMB',
'RIGHT_THUMB',
'LEFT_HIP',
'RIGHT_HIP',
'LEFT_KNEE',
'RIGHT_KNEE',
'LEFT_ANKLE',
'RIGHT_ANKLE',
'LEFT_HEEL',
'RIGHT_HEEL',
'LEFT_FOOT_INDEX',
'RIGHT_FOOT_INDEX']
with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:
while True:
ret, frame = cap.read()
if ret == False:
cap.release()
video_saver.release()
cv2.destroyAllWindows()
break
image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image.flags.writeable = False
results = pose.process(image)
image.flags.writeable = True
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
timestamp_name = str(cap.get(cv2.CAP_PROP_POS_MSEC))
try:
landmarks = results.pose_landmarks.landmark
CENTER_HEAD = (landmarks[mp_pose.PoseLandmark.NOSE.value].x, landmarks[mp_pose.PoseLandmark.NOSE.value].y, landmarks[mp_pose.PoseLandmark.NOSE.value].z)
LEFT_SHOULDER = (landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].y, landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].z)
RIGHT_SHOULDER = (landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].z)
LEFT_ELBOW = (landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].x, landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].y, landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].z)
RIGHT_ELBOW = (landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value].z)
LEFT_WRIST = (landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].x, landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].y, landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].z)
RIGHT_WRIST = (landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value].z)
LEFT_PINKY = (landmarks[mp_pose.PoseLandmark.LEFT_PINKY.value].x, landmarks[mp_pose.PoseLandmark.LEFT_PINKY.value].y, landmarks[mp_pose.PoseLandmark.LEFT_PINKY.value].z)
RIGHT_PINKY = (landmarks[mp_pose.PoseLandmark.RIGHT_PINKY.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_PINKY.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_PINKY.value].z)
LEFT_INDEX = (landmarks[mp_pose.PoseLandmark.LEFT_INDEX.value].x, landmarks[mp_pose.PoseLandmark.LEFT_INDEX.value].y, landmarks[mp_pose.PoseLandmark.LEFT_INDEX.value].z)
RIGHT_INDEX = (landmarks[mp_pose.PoseLandmark.RIGHT_INDEX.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_INDEX.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_INDEX.value].z)
LEFT_THUMB = (landmarks[mp_pose.PoseLandmark.LEFT_THUMB.value].x, landmarks[mp_pose.PoseLandmark.LEFT_THUMB.value].y, landmarks[mp_pose.PoseLandmark.LEFT_THUMB.value].z)
RIGHT_THUMB = (landmarks[mp_pose.PoseLandmark.RIGHT_THUMB.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_THUMB.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_THUMB.value].z)
LEFT_HIP = (landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].x, landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].y, landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].z)
RIGHT_HIP = (landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value].z)
LEFT_KNEE = (landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].x, landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].y, landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].z)
RIGHT_KNEE = (landmarks[mp_pose.PoseLandmark.RIGHT_KNEE.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_KNEE.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_KNEE.value].z)
LEFT_ANKLE = (landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].x, landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].y, landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].z)
RIGHT_ANKLE = (landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value].z)
LEFT_HEEL = (landmarks[mp_pose.PoseLandmark.LEFT_HEEL.value].x, landmarks[mp_pose.PoseLandmark.LEFT_HEEL.value].y, landmarks[mp_pose.PoseLandmark.LEFT_HEEL.value].z)
RIGHT_HEEL = (landmarks[mp_pose.PoseLandmark.RIGHT_HEEL.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_HEEL.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_HEEL.value].z)
LEFT_FOOT_INDEX = (landmarks[mp_pose.PoseLandmark.LEFT_FOOT_INDEX.value].x, landmarks[mp_pose.PoseLandmark.LEFT_FOOT_INDEX.value].y, landmarks[mp_pose.PoseLandmark.LEFT_FOOT_INDEX.value].z)
RIGHT_FOOT_INDEX = (landmarks[mp_pose.PoseLandmark.RIGHT_FOOT_INDEX.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_FOOT_INDEX.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_FOOT_INDEX.value].z)
coordinates_list.append(str(timestamp_name) + " : " + str({'CENTER_HEAD':CENTER_HEAD,
'LEFT_SHOULDER':LEFT_SHOULDER,
'RIGHT_SHOULDER':RIGHT_SHOULDER,
'LEFT_ELBOW':LEFT_ELBOW,
'RIGHT_ELBOW':RIGHT_ELBOW,
'LEFT_WRIST':LEFT_WRIST,
'RIGHT_WRIST':RIGHT_WRIST,
'LEFT_PINKY':LEFT_PINKY,
'RIGHT_PINKY':RIGHT_PINKY,
'LEFT_INDEX':LEFT_INDEX,
'RIGHT_INDEX':RIGHT_INDEX,
'LEFT_THUMB':LEFT_THUMB,
'RIGHT_THUMB':RIGHT_THUMB,
'LEFT_HIP':LEFT_HIP,
'RIGHT_HIP':RIGHT_HIP,
'LEFT_KNEE':LEFT_KNEE,
'RIGHT_KNEE':RIGHT_KNEE,
'LEFT_ANKLE':LEFT_ANKLE,
'RIGHT_ANKLE':RIGHT_ANKLE,
'LEFT_HEEL':LEFT_HEEL,
'RIGHT_HEEL':RIGHT_HEEL,
'LEFT_FOOT_INDEX':LEFT_FOOT_INDEX,
'RIGHT_FOOT_INDEX':RIGHT_FOOT_INDEX}))
except:
pass
mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
video_saver.write(image)
cv2.imshow("Video Feed", image)
cv2.waitKey(1)
v_split = video_file_path.split(".")
v_split[-1] = "txt"
v_split[-2] = v_split[-2] + "_coordinates"
coordinates_file_path = ".".join(v_split)
with open(coordinates_file_path, "w") as f:
f.write("\n".join(coordinates_list))
v_split = video_file_path.split(".")
v_split[-1] = "xlsx"
v_split[-2] = v_split[-2] + "_excel"
coordinates_excel_path = ".".join(v_split)
def get_vals(x):
vals = []
for i in x:
for j in i:
vals.append(j)
return vals
df = pd.DataFrame(coordinates_list)
df["frame"] = df[0].apply(lambda x: x.split(" : ")[0])
df[0] = df[0].apply(lambda x: get_vals(literal_eval(x.split(" : ")[1]).values()))
df_columns = []
mapper_dict = {0:"x", 1:"y", 2:"z"}
for keypoint in keypoints_list:
for i in range(0,3):
df_columns.append(keypoint+"_"+mapper_dict.get(i))
df = pd.concat([df["frame"], pd.DataFrame(df[0].to_list(), columns=df_columns)], axis=1)
df.to_excel(coordinates_excel_path, index=False)
#open_btn = Button( root, text="open File", command=open, borderwidth=0).pack()
ExportButton = Button(root, text="Track", command=tracking ,borderwidth=0 ,fg="blue")
ExportButton.pack()
root.mainloop()
.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')
My code is about to create an H5 file for Each and Every video in the folder, Extracting the feature from the video and stored into the H5 file.
in Below shown code extraction feature from multi videos and all the features are stored in the single H5 file
H5 file order:
video1:
- feature
video2:
- feature
issues:
How to create an H5 file for every video after a process is done
Code: Create_data.py
import argparse
from utils.generate_dataset import Generate_Dataset
parser = argparse.ArgumentParser(""Welcome you to fraction)
# Dataset options
parser.add_argument('--input', '--split', type=str, help="input video")
parser.add_argument('--output', type=str, default='', help="out data")
args = parser.parse_args()
if __name__ == "__main__":
gen = Generate_Dataset(args.input, args.output)
gen.generate_dataset()
gen.h5_file.close()
Code: Generate_Dataset.py :
import os
from networks.CNN import ResNet
from utils.KTS.cpd_auto import cpd_auto
from tqdm import tqdm
import math
import cv2
import numpy as np
import h5py
import numpy as np
class Generate_Dataset:
def __init__(self, video_path, save_path):
self.resnet = ResNet()
self.dataset = {}
self.video_list = []
self.video_path = ''
self.h5_file = h5py.File(save_path, 'w')
self._set_video_list(video_path)
def _set_video_list(self, video_path):
# import pdb;pdb.set_trace()
if os.path.isdir(video_path):
self.video_path = video_path
fileExt = r".mp4",".avi"
self.video_list = [_ for _ in os.listdir(video_path) if _.endswith(fileExt)]
self.video_list.sort()
else:
self.video_path = ''
self.video_list.append(video_path)
for idx, file_name in enumerate(self.video_list):
self.dataset['video_{}'.format(idx+1)] = {}
self.h5_file.create_group('video_{}'.format(idx+1))
def _extract_feature(self, frame):
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.resize(frame, (224, 224))
res_pool5 = self.resnet(frame)
frame_feat = res_pool5.cpu().data.numpy().flatten()
return frame_feat
def _get_change_points(self, video_feat, n_frame, fps):
n = n_frame / fps
m = int(math.ceil(n/2.0))
K = np.dot(video_feat, video_feat.T)
change_points, _ = cpd_auto(K, m, 1)
change_points = np.concatenate(([0], change_points, [n_frame-1]))
temp_change_points = []
for idx in range(len(change_points)-1):
segment = [change_points[idx], change_points[idx+1]-1]
if idx == len(change_points)-2:
segment = [change_points[idx], change_points[idx+1]]
temp_change_points.append(segment)
change_points = np.array(list(temp_change_points))
# temp_n_frame_per_seg = []
# for change_points_idx in range(len(change_points)):
# n_frame = change_points[change_points_idx][1] - change_points[change_points_idx][0]
# temp_n_frame_per_seg.append(n_frame)
# n_frame_per_seg = np.array(list(temp_n_frame_per_seg))
# print(change_points)
arr = change_points
list1 = arr.tolist()
list2 = list1[-1].pop(1) #pop [-1]value
print(list2)
print(list1)
print("****************") # [-1][-1] value find and divided by 15
cps_m = math.floor(arr[-1][1]/15)
list1[-1].append(cps_m) #append to list
print(list1)
print("****************") #list to nd array convertion
arr = np.asarray(list1)
print(arr)
arrmul = arr * 15
print(arrmul)
print("****************")
# print(type(change_points))
# print(n_frame_per_seg)
# print(type(n_frame_per_seg))
median_frame = []
for x in arrmul:
print(x)
med = np.mean(x)
print(med)
int_array = med.astype(int)
median_frame.append(int_array)
print(median_frame)
# print(type(int_array))
return arrmul
# TODO : save dataset
def _save_dataset(self):
pass
def generate_dataset(self):
print('[INFO] CNN processing')
for video_idx, video_filename in enumerate(self.video_list):
video_path = video_filename
if os.path.isdir(self.video_path):
video_path = os.path.join(self.video_path, video_filename)
video_basename = os.path.basename(video_path).split('.')[0]
video_capture = cv2.VideoCapture(video_path)
fps = video_capture.get(cv2.CAP_PROP_FPS)
n_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
frame_list = []
picks = []
video_feat = None
video_feat_for_train = None
for frame_idx in tqdm(range(n_frames-1)):
success, frame = video_capture.read()
if frame_idx % 15 == 0:
if success:
frame_feat = self._extract_feature(frame)
picks.append(frame_idx)
if video_feat_for_train is None:
video_feat_for_train = frame_feat
else:
video_feat_for_train = np.vstack((video_feat_for_train, frame_feat))
if video_feat is None:
video_feat = frame_feat
else:
video_feat = np.vstack((video_feat, frame_feat))
else:
break
video_capture.release()
arrmul = self._get_change_points(video_feat, n_frames, fps)
self.h5_file['video_{}'.format(video_idx+1)]['features'] = list(video_feat_for_train)
self.h5_file['video_{}'.format(video_idx+1)]['picks'] = np.array(list(picks))
self.h5_file['video_{}'.format(video_idx+1)]['n_frames'] = n_frames
self.h5_file['video_{}'.format(video_idx+1)]['fps'] = fps
self.h5_file['video_{}'.format(video_idx + 1)]['video_name'] = video_filename.split('.')[0]
self.h5_file['video_{}'.format(video_idx+1)]['change_points'] = arrmul
Expected results :
Folder: video
video_1:
video1.mp4
video2.mp4
Files are in this structure, now read video files and create separate H5 files after the process is over.
For more Code reference
You need to :
remove self.h5_file = h5py.File(save_path, 'w') from __init__()
remove self.h5_file.create_group('video_{}'.format(idx+1)) from _set_video_list()
remove gen.h5_file.close() from main()
change last block of generate_dataset() into something like:
.
video_capture.release()
arrmul = self._get_change_points(video_feat, n_frames, fps)
h5_dir = os.path.dirname(video_path)
h5_full_path = os.path.join(h5_dir, 'video_{}'.format(video_idx+1))
with h5py.File(h5_full_path, 'w') as h5_file:
h5_file['features'] = list(video_feat_for_train)
h5_file['picks'] = np.array(list(picks))
h5_file['n_frames'] = n_frames
h5_file['fps'] = fps
h5_file['video_name'] = video_filename.split('.')[0]
h5_file['change_points'] = arrmul
Please note that your inner video file indices and actual video file name numbers may not match. So I suggest to change
h5_dir = os.path.dirname(video_path)
h5_full_path = os.path.join(h5_dir, 'video_{}'.format(video_idx+1))
from above into
h5_full_path = video_path.split('.')[0] + '.h5'
This will create features file with the name matched to the video file.
guys! How are you? I have this code below and I'm having this trouble with the insertData function. This function is used to enter values from an excel spreadsheet into the tkinter treeview using Pandas. It's almost all right, but it's too slow and I don't know how to fix it. If anyone could help me, I'd be very happy.
Thanks in advance!
from tkinter import *
import ttk
import openpyxl
import pandas as pd
nuScreen = Tk()
nuScreen.title("ContrasinSystem - Usuário Comum")
nuScreen.iconbitmap("logocontransin.ico")
book = openpyxl.load_workbook('Registros.xlsx')
sheet = book.sheetnames
sh = book.active.cell
#Contador de Linhas:
wb2 = openpyxl.load_workbook('Registros.xlsx')
sheet2 = wb2.worksheets[0]
rowCount = sheet2.max_row
v = []
#Design:
class main():
def __init__(self,tk):
for x in range (0,len(sheet)):
v.append(sheet[int(x)])
self.wb2 = openpyxl.load_workbook('Registros.xlsx')
self.sheet2 = self.wb2.worksheets[0]
self.row_count = self.sheet2.max_row
self.column_count = self.sheet2.max_column
self.nuFrame = Frame(nuScreen, width = 1500, height = 450)
self.nuFrame.pack()
self.img = PhotoImage(file="logocontransin.png")
self.w = Label(self.nuFrame, image = self.img)
self.w.img = self.img
self.w.place(x=65,y=150)
self.srchlbl = ttk.Label(self.nuFrame, text = "Buscar:")
self.srchlbl.place(x=25,y=75)
self.srchetr = ttk.Entry(self.nuFrame, width = 30)
self.srchetr.place(x=75,y=75)
self.treeview = ttk.Treeview(self.nuFrame)
self.treeview.place(x=300,y=75, width = 1100)
dataVector = []
def columnsName():
def Header():
self.columnVector = []
self.dataVector = []
teste = []
self.treeview.column("#0", width = 20)
self.columnHeader = pd.read_excel(r'Registros.xlsx', str(self.cmb.get()), header_only = True, nrows=0).columns
for a in self.columnHeader:
self.columnVector.append(a)
self.treeview.configure(columns = self.columnVector)
for b in self.columnHeader:
self.treeview.heading(str(b), text = str(b))
def insertData():
for m in range(rowCount):
self.dataValues = pd.read_excel(r'Registros.xlsx',str(self.cmb.get()), skip_blank_lines=True, skiprows=0)
for l in self.dataValues:
dataVector.append(l)
self.treeview.insert("", "end",values = dataVector)
print(self.dataValues)
Header()
insertData()
self.cmbLbl = ttk.Label(self.nuFrame, text = "Assunto:")
self.cmbLbl.place(x=1200, y=325)
self.cmb = ttk.Combobox(self.nuFrame, values = v)
self.cmb.place(x=1250,y=325)
self.btncmb = ttk.Button(self.nuFrame, text = "Buscar", command = columnsName)
self.btncmb.place(x=1320,y=375)
nuScreen.geometry("1500x450")
main(nuScreen)
nuScreen.mainloop()
How many times do you want to open a excel file for reading?
def insertData():
for m in range(rowCount):
self.dataValues = pd.read_excel(r'Registros.xlsx',str(self.cmb.get()),
skip_blank_lines=True, skiprows=0)
for l in self.dataValues:
dataVector.append(l)
self.treeview.insert("", "end",values = dataVector)
print(self.dataValues)
Should you instead omit the first loop?
def insertData():
self.dataValues = pd.read_excel(r'Registros.xlsx',str(self.cmb.get()),
skip_blank_lines=True, skiprows=0)
for l in self.dataValues:
self.treeview.insert("", "end",values = l)
print(self.dataValues)
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!