How to use image_import method in tempest

Best Python code snippet using tempest_python

Entregable_Final.py

Source:Entregable_Final.py Github

copy

Full Screen

1from tkinter.font import BOLD2import cv23from matplotlib import pyplot as plt4from static_functions import *5from tkinter import *6from tkinter import filedialog7from PIL import Image8from PIL import ImageTk9from time import time10import os11import imutils12from kalmanfilter import KalmanFilter13eye_detector = EyeDetector()14kf = KalmanFilter()15global saved16saved = []17################# GUI#########################18def visualizar():19 global cap,ojo1_x,ojo1_y,ojo2_x,ojo2_y,path,save,img___,path_img, saved_img,change20 global scaled_eye_x,scaled_eye_y21 global previous_time,current_time,count,init_time22 ret,frame = cap.read()23 if ret == True:24 eyes = eye_detector.eye_coords(frame)25 if eyes is not None:26 ( (ojo1_x, ojo1_y), (ojo2_x, ojo2_y) ), ( scaled_eye_x, scaled_eye_y) = eyes27 scaled_eye_x = 1-scaled_eye_x28 29 frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)30 #### resize frame 31 frame = cv2.resize(frame,(75,50))32 ###########33 34 im = Image.fromarray(frame)35 img = ImageTk.PhotoImage(image=im)36 lblvideo.configure(image=img)37 lblvideo.image=img38 39 ##### modificación de parametros de imagen importada 40 #### leer la imagen41 42 current_time=time()43 if count==0:44 saved_img = None45 if count!=0:46 change=write_to_file(scaled_eye_x,scaled_eye_y,count,change,current_time,init_time)47 48 49 if (current_time-previous_time>7) and (count<6):50 51 path_img = path +img___[count]52 count +=153 change=True54 saved_img = None55 previous_time = time()56 elegir_img()57 if (count==6) and ((current_time-previous_time>7)):58 print('finalizar')59 finalizar()60 else:61 if saved_img is None:62 image_imported =cv2.imread(path_img)63 64 image_imported = cv2.resize(image_imported,(screen_width,screen_height))65 image_imported = imutils.resize(image_imported,height=screen_height) #"""height=400"""66 #### visualizar la imagen de entrada en la GUI67 image_imported = imutils.resize(image_imported,width=screen_width)68 image_imported = cv2.cvtColor(image_imported,cv2.COLOR_BGR2RGB)69 saved_img = image_imported.copy()70 else:71 image_imported = saved_img.copy()72 predicted = kf.predict(screen_width*scaled_eye_x,screen_height*scaled_eye_y)73 image_import = cv2.circle(image_imported,(int(predicted[0]),int(predicted[1])),5,(0,0,255),4)74 saved = []75 76 im = Image.fromarray(image_import)77 img = ImageTk.PhotoImage(image=im)78 lblInputImage.configure(image=img)79 lblInputImage.image = img80 cv2.waitKey(0)81 lblInputImage.configure(image=img)82 lblInputImage.image = img83 ojo1_value_x.configure(text='{:.2f}'.format(ojo1_x),font=BOLD)84 ojo1_value_y.configure(text="{:.2f}".format(ojo1_y),font=BOLD)85 ojo2_value_x.configure(text='{:.2f}'.format(ojo2_x),font=BOLD)86 ojo2_value_y.configure(text='{:.2f}'.format(ojo2_y),font=BOLD)87 lblvideo.after(1,visualizar)88 else:89 lblvideo.image = ''90 lblInfoVideoPath.configure(text='')91 rad1.configure(state='active')92 rad2.configure(state='active')93 selected.set(0) ### esto es para que no este seleccionado ningujo 94 #### de las redondas95 boton_end.configure(state='active')96 cap.release()97def elegir_img():98 global path_img,path,img___99 global ojo1_x,ojo1_y100 101 if len(path_img) >0:102 103 #### leer la imagen104 105 image_imported =cv2.imread(path_img)106 image_imported = cv2.resize(image_imported,(screen_width,screen_height))107 image_imported = imutils.resize(image_imported,height=screen_height) #"""height=400"""108 #### visualizar la imagen de entrada en la GUI109 image_imported = imutils.resize(image_imported,width=screen_width)#width=800)110 111 image_imported = cv2.cvtColor(image_imported,cv2.COLOR_BGR2RGB)112 image_import = cv2.circle(image_imported,((int(screen_width/2)),(int(screen_height/2)-50)),7,(0,0,255),4)113 im = Image.fromarray(image_import)114 img = ImageTk.PhotoImage(image=im)115 lblInputImage.configure(image=img)116 lblInputImage.image = img117 return118def video_de_entrada(): #Aqui esta el array de fotos119 global cap,threshold,image_imported,path,img___,path_img120 global ojo1_value_x,ojo1_value_y,ojo2_value_x,ojo2_value_y121 global previous_time,current_time,count,init_time122 path = os.path.join(os.getcwd(),"img_prototype")123 img___ = [124 "/001.jpg",125 "/002.jpg",126 "/003.jpg",127 "/004.jpg",128 "/005.jpg",129 "/006.jpg"130 ]131 #image_imported =cv2.imread()132 if selected.get() == 1: 133 boton_end.configure(state='active')134 path_img=path+img___[0]135 elegir_img()136 previous_time = time() ### tiempo inicial 137 count = 0 ## contando el número de imagenes138 139 if selected.get() == 2: 140 rad1.configure(state='disabled')141 rad2.configure(state='disabled')142 boton_end.configure(state='active')143 lblInfoVideoPath.configure(text='')144 cap = cv2.VideoCapture(0)145 init_time = time()146 visualizar()147def finalizar():148 global init_time,current_time149 print('finalizar')150 lblInfoVideoPath.configure(text='')151 lblvideo.image=''152 lblInfoVideoPath.configure(text='')153 154 rad1.configure(state='active')155 rad2.configure(state='active')156 boton_end.configure(state='disabled')157 lblInputImage.image = ''158 selected.set(0)159 cap.release()160 ojo1_value_x.configure(text='0')161 ojo1_value_y.configure(text='0')162 ojo2_value_x.configure(text='0')163 ojo2_value_y.configure(text='0')164 write_to_file(screen_width,screen_height,50,current=current_time,previous=init_time,change=True,)165 #guardar_images()166def guardar_images():167 f = open("logs.txt",'r')168 variable= True169 all_data ={}170 for i in range(7):171 imagen=[]172 while variable:173 line = f.readline()174 if line=="\n":175 break176 177 if line[0]!='I' and line[0]!='T': 178 dato=line.split(sep='\n')[0].split(sep=',')179 imagen.append([float(dato[0]),float(dato[1])])180 # print('dato')181 if i==6 and (line[0]!='I' and line[0]!='T'):182 dato=line.split(sep='\n')[0].split(sep=',')183 imagen.append([float(dato[0]),float(dato[1])])184 variable=False185 variable=True186 all_data[i]=imagen187 ### filtro de información188 print(all_data)189 screen_width=all_data[6][0][0]190 screen_height=all_data[6][0][1]191 path = os.path.join(os.getcwd(),"img_prototype")192 img___ = [193 "/001.jpg",194 "/002.jpg",195 "/003.jpg",196 "/004.jpg",197 "/005.jpg",198 "/006.jpg"199 ]200 for i in range(len(img___)):201 #### leer la imagen202 print(path+img___[i])203 image_imported =cv2.imread(path+img___[i])204 print(image_imported)205 image_imported = cv2.resize(image_imported,(int(screen_width),int(screen_height)))206 image_imported = imutils.resize(image_imported,height=int(screen_height)) #"""height=400"""207 #### visualizar la imagen de entrada en la GUI208 image_imported = imutils.resize(image_imported,width=int(screen_width))#width=800)209 210 #image_imported = cv2.cvtColor(image_imported,cv2.COLOR_BGR2RGB)211 212 #image_import = cv2.circle(image_imported,((int(screen_width/2)),(int(screen_height/2)-50)),7,(0,0,255),cv2.FILLED) #4213 image_import = None214 for j in range(len(all_data[i])):215 x = all_data[i][j][0]216 y = all_data[i][j][1]217 218 if j==0:219 image_import = cv2.circle(image_imported,((int(screen_width*x)),(int(screen_height*y))),7,(0,255,0),4)220 else:221 image_import = cv2.circle(image_import,((int(screen_width*x)),(int(screen_height*y))),7,(0,255,0),4)222 cv2.imwrite(f'{i} '+'view.jpg',image_import)223def gui():224 global cap,selected,IblInfo1,lblInfoVideoPath,rad1,rad2,boton_end,boton_upload_file,boton_upload_file225 global lblInputImage,lblvideo,entrada_1,threshold226 global cap,ojo1_x,ojo1_y,ojo2_x,ojo2_y227 global screen_width,screen_height ### obtención de tamaño de pantalla228 global ojo1_value_x,ojo1_value_y,ojo2_value_x,ojo2_value_y,change,init_time229 ojo1_x=0230 ojo1_y=0231 ojo2_x=0232 ojo2_y=0233 234 change=True ### el valor de cambio inicial para imagenes235 cap = None236 root = Tk()237 IblInfo1 = Label(root,text='Entrada de Video',font='Bold')238 IblInfo1.grid(column=0,row=0,columnspan=1)239 240 selected = IntVar()241 rad1 = Radiobutton( ### para adjuntar imagen242 root,243 text='Inicializar visualización',244 width=20,245 variable=selected,246 value=1,247 command=video_de_entrada248 )249 rad2 = Radiobutton( ## para poder visualizar la imagen de video250 root, 251 text='Ver Video en Vivo',252 width=20,253 variable=selected,254 value=2,255 command=video_de_entrada256 )257 rad1.grid(column=0,row=1,padx=0)258 rad2.grid(column=0,row=2,padx=0)259 ########## mostrar el pad del videos260 lblInfoVideoPath = Label(root,text='',width=20)261 lblInfoVideoPath.grid(column=2,row=1)262 lblvideo = Label(root)263 lblvideo.grid(column=2,row=0,columnspan=2,rowspan=3)264 ################### segmentar donde se mostrará la imagen################265 lblInputImage=Label(root)266 lblInputImage.grid(column=0, row=3,pady=0,columnspan=5)267 ############ mostrar el botón para finalizar visualización###########268 boton_end = Button(269 root,270 text='Finalizar Visualización y limpiar',271 state='active',272 command=finalizar273 )274 boton_end.grid(column=1,row=0)275 ########## labels para ojo 1 y ojo 2 276 ojo_1_label = Label(root,text='Ojo 1')277 ojo_1_label.grid(column=2,row=0)278 ojo_2_label=Label(root,text='Ojo 2')279 ojo_2_label.grid(column=2,row=1)280 ####### visualizar posicion de ojos x e y 281 ojo1_value_x = Label(root,text=f'{ojo1_x}')282 ojo1_value_y = Label(root,text=f'{ojo1_y}')283 ojo2_value_x = Label(root,text=f'{ojo2_x}')284 ojo2_value_y = Label(root,text=f'{ojo2_y}')285 286 ojo1_value_x.grid(column=3,row=0)287 ojo1_value_y.grid(column=4,row=0)288 ojo2_value_x.grid(column=3,row=1)289 ojo2_value_y.grid(column=4,row=1)290 #### tamaño de la pantalla obtención de datos291 screen_width = root.winfo_screenwidth()292 screen_height = root.winfo_screenheight() -150293 ################ Visualizando los valores en ojo izquierdo y ojo derecho ##############294 root.mainloop()...

Full Screen

Full Screen

Option_4_Num_3_4.py

Source:Option_4_Num_3_4.py Github

copy

Full Screen

12import matplotlib.pyplot as plt3import matplotlib.image as mpimg4from keras.models import load_model5from keras.preprocessing.image import load_img6from keras.preprocessing.image import img_to_array78#################################################[RESOURCES]#################################################9# CIFAR-10 tutorial and database #10# https://machinelearningmastery.com/how-to-develop-a-cnn-from-scratch-for-cifar-10-photo-classification/ #11# https://www.cs.toronto.edu/~kriz/cifar.html #12#############################################################################################################1314# load and prepare the image15def load_image(filename):16 img = load_img(filename, target_size=(32, 32)) # Load the target image17 img = img_to_array(img) # Convert the image to an array18 img = img.reshape(1, 32, 32, 3) # Reshape into a 3-channel sample19 img = img.astype('float32') # Prepare pixel data20 img = img / 255.021 22 return img2324# This function allows multiple images to be processed 25def multiprocessing():26 while(True): 27 run_example()28 plt.show(block=True)29 30 exit_statement=input("Enter 'q' if you would like to quit or press any key to continue.")31 32 if (exit_statement.lower()=='q'):33 break34 else:35 print("Program will continue")36 37 return None3839# This function calculates the percent match of each image for each category40def getPercentage(prediction_class,index):41 42 i = index43 percentage = round(prediction_class[0][i]*100,3)44 45 return percentage4647# This function loads the chosen image and makes a prediction of what the image is48def run_example():49 print("Please make a selection on the menu below\n") # Displays the menu and takes user input50 choose = input('''\t\tMenu: 51 -----------------------------------52 1: Airplane_1_database_processed53 2: Airplane_2_database_processed54 3: Automobile_1_database_processed55 4: Automobile_2_database_processed56 5: Bird_1_database_processed57 6: Bird_2_database_processed58 7: Cat_1_database_processed59 8: Cat_2_database_processed60 9: Deer_1_database_processed61 10: Deer_2_database_processed62 11: Dog_1_database_processed63 12: Dog_2_database_processed64 13: Frog_1_database_processed65 14: Frog_2_database_processed66 15: Horse_1_database_processed67 16: Horse_2_database_processed68 17: Ship-1_database_processed69 18: Ship_2_database_processed70 19: Truck_1_database_processed71 20: Truck_2_database_processed72 -------------------------------------73 Enter here:''') 7475 try: # try block to check valid user input76 options=int(choose) 77 if (options == 1):78 image_import ='Airplane_1_database_processed'79 if (options == 2):80 image_import ='Airplane_2_database_processed' 81 if (options == 3):82 image_import ='Automobile_1_database_processed'83 if (options == 4):84 image_import ='Automobile_2_database_processed' 85 if (options == 5):86 image_import ='Bird_1_database_processed'87 if (options == 6):88 image_import ='Bird_2_database_processed' 89 if (options == 7):90 image_import ='Cat_1_database_processed'91 if (options == 8):92 image_import ='Cat_2_database_processed'93 if (options == 9):94 image_import ='Deer_1_database_processed'95 if (options == 10):96 image_import ='Deer_2_database_processed' 97 if (options == 11):98 image_import ='Dog_1_database_processed'99 if (options == 12):100 image_import ='Dog_2_database_processed' 101 if (options == 13):102 image_import ='Frog_1_database_processed'103 if (options == 14):104 image_import ='Frog_2_database_processed' 105 if (options == 15):106 image_import ='Horse_1_database_processed'107 if (options == 16):108 image_import ='Horse_2_database_processed'109 if (options == 17):110 image_import ='Ship_1_database_processed'111 if (options == 18):112 image_import ='Ship_2_database_processed' 113 if (options == 19):114 image_import ='Truck_1_database_processed'115 if (options == 20):116 image_import='Truck_2_database_processed' 117 118 image = load_image(''+image_import+'.png') # Call the load_image function 119 model = load_model('final_model.h5') # Load the model using keras120 result = model.predict_classes(image) # Predict the class the image falls into121 plt.imshow(mpimg.imread(''+image_import+'.png'))122 prediction_class = model.predict_proba(image) # Calculate the class probability for the object123 124# Call the getPercentage function for each category125######################################################################################################################126 airplane_stats = getPercentage(prediction_class,0) 127 automobile_stats = getPercentage(prediction_class,1)128 bird_stats = getPercentage(prediction_class,2)129 cat_stats = getPercentage(prediction_class,3)130 deer_stats = getPercentage(prediction_class,4)131 dog_stats = getPercentage(prediction_class,5)132 frog_stats = getPercentage(prediction_class,6)133 horse_stats = getPercentage(prediction_class,7)134 ship_stats = getPercentage(prediction_class,8)135 truck_stats = getPercentage(prediction_class,9)136######################################################################################################################137 138# Display the results in the console window139######################################################################################################################140 print("\nImage:",image_import,"\nMaking Prediction....\n")141 print("Image Prediction:")142 print(f"Airplane: {airplane_stats}%")143 print(f"Automobile: {automobile_stats}%")144 print(f"Bird: {bird_stats}%")145 print(f"Cat: {cat_stats}%")146 print(f"Deer: {deer_stats}%")147 print(f"Dog: {dog_stats}%")148 print(f"Frog: {frog_stats}%")149 print(f"Horse: {horse_stats}%")150 print(f"Ship: {ship_stats }%")151 print(f"Truck: {truck_stats}%")152######################################################################################################################153 154 print("\nClasses: ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']")155 print("Class:",result[0],'\n')156 157 placeMarker = int(result[0])158 159 if (placeMarker == 0):160 print("This is an airplane") 161 if (placeMarker == 1):162 print("This is an automobile") 163 if (placeMarker == 2):164 print("This is a bird") 165 if (placeMarker == 3):166 print("This is a cat.") 167 if (placeMarker == 4):168 print("This is a deer.") 169 if (placeMarker == 5):170 print("This is a dog.") 171 if (placeMarker == 6):172 print("This is a frog.") 173 if (placeMarker == 7):174 print("This is a horse.") 175 if (placeMarker == 8):176 print("This is a ship.") 177 if (placeMarker == 9):178 print("This is a truck.")179180 except ValueError: 181 print("Error: a non-integer value was entered.\n"182 "Please only enter a valid integer between 1 and 20")183 except UnboundLocalError:184 print("Error: This integer is out of the given range.\n"185 "Please only enter a valid integer between 1 and 20")186 187 return None188def main():189 190 user_choice = input("Would you like to enable multi-image processing? Type: 'y', or type 'n' for single image processing:")191192 if(user_choice.lower()=='y'):193 multiprocessing() 194 elif(user_choice.lower()=='n'):195 run_example()196 else:197 print("Please make a valid selection")198 main()199 200if __name__ == '__main__': ...

Full Screen

Full Screen

test.py

Source:test.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import vtk3import numpy as np4import libtiff as lt5class MyStyle(vtk.vtkInteractorStyleImage):6 def __init__(self, parent=None):7 print "ddd"8 self.AddObserver("LeftButtonPressEvent", self.leftButtonDown)9 self.AddObserver("MouseWheelForwardEvent", self.forward_fun)10 self.AddObserver("MouseWheelBackwardEvent", self.backward_fun)11 12 13 def forward_fun(self, *arg):14 s = imageViewer.GetSlice()15 n = s + 116 if n > 511:17 n = 018 imageViewer.SetSlice(n)19 20 def backward_fun(self, *arg):21 s = imageViewer.GetSlice()22 n = s - 123 if n < 0:24 n = 51125 imageViewer.SetSlice(n)26 27 def leftButtonDown(self, *arg):28 inter1 = self.GetInteractor()29 click_pos = inter1.GetEventPosition()30 s = imageViewer.GetSlice()31# print imageViewer.GetSize()32# print imageViewer.GetImageActor().GetBounds()33# image_data.SetScalarComponentFromFloat(click_pos[0], click_pos[1], s, 0, 255.0)34# image_data.SetScalarComponentFromFloat(click_pos[0] + 1, click_pos[1], s, 0, 255.0)35# image_data.SetScalarComponentFromFloat(click_pos[0], click_pos[1] + 1, s, 0, 255.0)36# image_data.SetScalarComponentFromFloat(click_pos[0] - 1, click_pos[1], s, 0, 255.0)37# image_data.SetScalarComponentFromFloat(click_pos[0], click_pos[1] - 1, s, 0, 255.0)38# image_import.Modified()39# image_import.Update()40# imageViewer.SetInput(image_import.GetOutput())41# imageViewer.Render()42 picker = vtk.vtkCellPicker()43 picker.Pick(click_pos[0], click_pos[1], s, imageViewer.GetRenderer())44 pos = picker.GetPickPosition()45 print pos46 sphereSource = vtk.vtkSphereSource()47 sphereSource.SetCenter(pos[0], pos[1], pos[2])48 sphereSource.SetRadius(1)49 sphereMapper = vtk.vtkPolyDataMapper()50 sphereMapper.SetInputConnection(sphereSource.GetOutputPort())51 sphereActor = vtk.vtkActor()52 sphereActor.SetMapper(sphereMapper)53 sphereActor.GetProperty().SetColor(255.0, 0.0, 0.0)54 imageViewer.GetRenderer().AddActor(sphereActor)55 imageViewer.Render()56def fun1():57 print "ddddd"58global i, imageViewer59i = 10060Tiff = lt.TIFF3D.open('G:\\sulei\\workplace\\Swc\\res\\22_24_12.tif', 'r')61images = Tiff.read_image()62image_import = vtk.vtkImageImport()63images = np.require(images, dtype=np.uint8)64images_string = images.tostring()65image_import.CopyImportVoidPointer(images_string, len(images_string))66image_import.SetDataScalarTypeToUnsignedChar()67image_import.SetDataExtent(0, 511, 0, 511, 0, 511)68image_import.SetWholeExtent(0, 511, 0, 511, 0, 511)69image_import.SetNumberOfScalarComponents(1)70image_import.Update()71image_data = image_import.GetOutput()72#image_data1 = vtk.vtkImageData()73#image_data1.DeepCopy(image_data)74style = MyStyle()75irenWin = vtk.vtkRenderWindowInteractor()76 77#style = vtk.vtkInteractorStyleImage()78#style.SetInteractionModeToImageSlicing()79#style.AddObserver("LeftButtonPressEvent", fun1)80#irenWin.SetInteractorStyle(style)81imageViewer = vtk.vtkImageViewer2()82imageViewer.SetInput(image_data)83imageViewer.SetupInteractor(irenWin)84imageViewer.SetColorLevel(50)85imageViewer.SetColorWindow(100)86imageViewer.SetSlice(i)87imageViewer.SetSliceOrientationToXY()88imageViewer.Render()89irenWin.SetInteractorStyle(style) #the location is important...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tempest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful