def execute(*args): """Test all derived functions for proper operation """ import Vector reload(Vector) Vector.test() import Add reload(Add) Add.test() import Multiply reload(Multiply) Multiply.test() import Divide reload(Divide) Divide.test() import Difference reload(Difference) Difference.test() import Poly reload(Poly) Poly.test() import Average reload(Average) Average.test() import LinTrans reload(LinTrans) LinTrans.test() import Test reload(Test) Test.test() import Rotate reload(Rotate) Rotate.test() import Magnitude reload(Magnitude) Magnitude.test() import Cape reload(Cape) Cape.test() print "-"*60 print "Function Test Complete"
def execute(*args): """Test all derived functions for proper operation """ import Vector reload(Vector) Vector.test() import Add reload(Add) Add.test() import Multiply reload(Multiply) Multiply.test() import Divide reload(Divide) Divide.test() import Difference reload(Difference) Difference.test() import Poly reload(Poly) Poly.test() import Average reload(Average) Average.test() import LinTrans reload(LinTrans) LinTrans.test() import Test reload(Test) Test.test() import Rotate reload(Rotate) Rotate.test() import Magnitude reload(Magnitude) Magnitude.test() import Cape reload(Cape) Cape.test() print "-" * 60 print "Function Test Complete"
def __init__(self, size=1): bpy.ops.object.select_all(action='DESELECT') # BB8 #bpy.ops.import_scene.obj(filepath=config.DATA_PATH + 'BB8/bb8.obj') bpy.ops.import_scene.obj(filepath=config.DATA_PATH + 'rob/rob.obj') bpy.context.scene.objects.active = bpy.context.selected_objects[0] bpy.ops.object.join() bpy.ops.transform.resize(value=(size, size, size)) # BB8 #bpy.ops.transform.rotate(value=-math.pi/2, axis=(0,0,1)) bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_VOLUME') self.data = bpy.context.object self.data.name = 'robot' # sensors ---------------------------------- self.sensor_wall = WallSensor.WallSensor(number_of_features=4) self.sensor_fruit = FruitSensor.FruitSensor(number_of_features=2, radius=1.5) # actuators -------------------------------- self.act_walk = Walk.Walk(velocity=0.05) self.act_rotate = Rotate.Rotate(degree_rotation=math.pi / 10) self.act_mouth = Mouth.Mouth(robot_size=0.03) # brain ------------------------------------ self.brain = Brain.Brain(number_of_actions=4)
def get_Occupancy_and_Coordinates(img): ######################################################## #this part needs to take in an image when Mission Planner tells it to #ergo it needs to be changed, or does mission planenr pass in a #ready to go image? # #filename = 'img' #img = cv2.imread(filename) #gray = cv2.imread(filename, 0) ######################################################## #Get the angle of rotation needed and rotate #rotated image is really the thing we need because it will be the best final image to use theta = baseLine.findAngle(img) rotatedImage = Rotate.rotateImage(theta) #Find all the lines of the squares imgWithEdges = edgechesshc.addEdges(rotatedImage) #Get all the coordinates of the keypoints coordinates = findCoordinates.getCoordinates(imgWithEdges) #Pass coordinates on to Squares squares = Squares.populateSquares(coordinates) #believe this step is no longer necessary because of the architecture #Load squares with their starting state #Squares.loadPieces(squares, pieceTypeArray) squaresCropped = Squares.getSquaresCropped(squares, rotatedImage) new_occupancy_grid, array_of_coordinates = FindPiece.main(squaresCropped) return new_occupancy_grid, array_of_coordinates
def makeSquareObjects(self, img): #######################initialize############################## #Take in image file ''' take in file img to initialize then run it throught the same ''' #somehow filename needs to take in a new image work through tomorrow filename = 'img' img = cv2.imread(filename) gray = cv2.imread(filename, 0) #Get the angle of rotation needed and rotate #rotated image is really the thing we need because it will be the best final image to use theta = baseLine.findAngle(filename) rotatedImage = Rotate.rotateImage(theta) #Save the rotated image cv2.imwrite('lib/rotated.jpg', rotatedImage) #Find all the lines of the squares imgWithEdges = edgechesshc.addEdges('lib/rotated.jpg') #Get all the coordinates of the keypoints coordinates = findCoordinates.getCoordinates(imgWithEdges) #Pass coordinates on to Squares squares = Squares.populateSquares(coordinates) #Load squares with their starting state Squares.loadPieces(squares, pieceTypeArray) squaresCropped = Squares.getSquaresCropped(squares, rotatedImage) self.new_piece_attribute, array_of_coordinates = FindPiece.main(squaresCropped) return squares
def makeSquareObjects(self, img): #######################initialize############################## #Take in image file ''' take in file img to initialize then run it throught the same ''' #somehow filename needs to take in a new image work through tomorrow filename = 'img' img = cv2.imread(filename) gray = cv2.imread(filename, 0) #Get the angle of rotation needed and rotate #rotated image is really the thing we need because it will be the best final image to use theta = baseLine.findAngle(filename) rotatedImage = Rotate.rotateImage(theta) #Save the rotated image cv2.imwrite('lib/rotated.jpg', rotatedImage) #Find all the lines of the squares imgWithEdges = edgechesshc.addEdges('lib/rotated.jpg') #Get all the coordinates of the keypoints coordinates = findCoordinates.getCoordinates(imgWithEdges) #Pass coordinates on to Squares squares = Squares.populateSquares(coordinates) #Load squares with their starting state Squares.loadPieces(squares, self.pieceTypeArray) squaresCropped = Squares.getSquaresCropped(squares, rotatedImage) self.new_piece_attribute, array_of_coordinates = FindPiece.main(squaresCropped) return squares
def handleImage(photoPath): # print '### photoPath: {}'.format(photoPath) returnOrientation = [] photoOrientation = None # print("*** {}".format(photoPath)) photoOrientation = Rotate.askPhotoOrientation(photoPath['InputThumb']) if photoOrientation.isdigit(): # imageRotated = Image.open(photoPath['InputOriginal']).rotate(int(photoOrientation) * 90,expand=True) # shutil.copyfile(photoPath['Input'],photoPath['Processed']) # if photoOrientation == '0': # # shutil.copyfile(photoPath['InputOriginal'],photoPath['Output']) # p = Process(target = shutil.copyfile,args = (photoPath['InputOriginal'],photoPath['Output'])) # p.start() # else: # p = Process(target = pilSaveHelper,args = (imageRotated,photoPath['Output'])) # p.start() # if photoOrientation != '0': # img = Image.open(photoPath['InputThumb']).rotate(int(photoOrientation) * 90)#,expand=True) # img.save(photoPath['InputThumb'],'JPEG',quality = 100) returnOrientation.append({'InputOriginal':photoPath['InputOriginal'],'Output':photoPath['Output'],'Orientation':photoOrientation}) # os.remove(photoPath['Input']) #save in two places, remove input elif photoOrientation == 'd': #delete photo returnOrientation.append({'InputOriginal':photoPath['InputOriginal'],'Output':photoPath['Output'],'Orientation':"-1"}) elif photoOrientation == 'z' and photoPath['photoPathIO_prev']: returnOrientation += handleImage(photoPath['photoPathIO_prev']) returnOrientation += handleImage(photoPath) #this photoPath must be redone because the command was 'z' RotationLog.appendRotationLog([photoPath['InputOriginal']]) # print 'rotationOrientation: {0}'.format(returnOrientation) return returnOrientation
def main(): #######################initialize############################## #Take in image file ''' take in file img to initialize then run it throught the same ''' filename = 'lib/chessanglesmall.jpg' img = cv2.imread(filename) #newimage = cv2.resize(img, (640,480)) showImage('img', img) cv2.waitKey(0) #gray = cv2.imread(filename, 0) #Get the angle of rotation needed and rotate theta = baseLine.findAngle(filename) rotatedImage = Rotate.rotateImage(theta, img) showImage('rotated image', rotatedImage) cv2.waitKey(0) cv2.destroyAllWindows() #Save the rotated image cv2.imwrite('lib/rotated.jpg', rotatedImage) #Find all the lines of the squares imgWithEdges = edgechesshc.addEdges('lib/rotated.jpg') #Get all the coordinates of the keypoints coordinates = findCoordinates.getCoordinates(imgWithEdges) #Pass coordinates on to Squares squares = Squares.populateSquares(coordinates) #Load squares with their starting state Squares.loadPieces(squares, new_piece_attribute, pieceTypeArray) ########################repeatedProcess############################ #at the end of all repeated processes we need to shift all the "new" #stuff into the "old" stuff we are using for reference and comparison #Find where the peices lie on the board #replace with updated image newImage = cv2.imread('lib/rotated.jpg') squaresCropped = Squares.getSquaresCropped(squares, newImage) print type(squaresCropped) piece_attribute_array, centerOfPiece = FindPiece.main(squaresCropped) #the arrayOfBooleans is T or F if there is a piece in a square #centerofpeice is an array of coordinates for the cetner of each piece (catch is it has to be perfectly centered on top of the piece) #print arrayOfBooleans #print centerOfPiece #print array_of_colors print piece_attribute_array print pieceTypeArray #Manage old and new images first #pieceTypeArray = findDifferencesArrays(oldBool, newBool, pieceType) ####################################finalProcess to start up again####################################3 ####We have to come up with a way to determine who moved, white or balck so that we can send it to AI ###########we will have to constantly update piecetype array as well and boolAray finalFE = Squares.giveForsythEdwardsNotation(pieceTypeArray, w_or_b_turn) ai_move = chess_ai.get_chess_move(finalFE, ROBOTCOLOR) ''' ##############How to do this##################################### if (w_or_b_turn == 'w'): w_or_b_turn == 'b' elif(w_or_b_turn == 'b'): w_or_b_turn == 'w' ''' print ai_move ############################Testing############################## #Show all the important images showImage('original', img) showImage('rotated', rotatedImage) showImage('image with edges', imgWithEdges) #Show all the cropped images #Squares.printCroppedSquares(squaresCropped) cv2.waitKey(0) cv2.destroyAllWindows()
Поворачивает на 31 градус все файлы форматов (не с расширенями!) jpg и png, находящиеся в директории ~/test/pics. 17.07.15 Параметр —inverse говорит, что в изображениях также нужно инвертировать соответствующий цветовой канал. Примеры: --inverse r --inverse b,g --inverse r,b,g Сочетания из r,g,b могут быть любые. """ import argparse import Rotate # функция , в которой поворот и инверсия parser = argparse.ArgumentParser( description="Turn and invert pictures with formats .jpg or .png" ) # сначала создаем переменную для добавления новых команд parser.add_argument("directory", help="Folder that contains pictures" ) #Добавляем новый аргумент конмадной строки """ parser.add_argument("degree", type=int, default=0, help="What degree?") parser.add_argument( "--inverse", type=str, help="Parametrs: r - red color, g - green color, b - black color") args = parser.parse_args() #теперь это можно вводить в консоль Rotate.all_files( args.directory, args.degree, args.inverse ) # файлы формата jpg и png поворачивает на N радусов и инвертирует нужные нам каналы #принимает путь градусы и инвертируемые каналы """ #args = parser.parse_args() #ВСе вводится с командной строки стначала путь в конце не забудь \ дальше пишешь число градусов а потом --inverse "r,g,b" запомни, что это строчка и через запятые""""
""" python prog.py D:/test/pics 31 —inverse r Поворачивает на 31 градус все файлы форматов (не с расширенями!) jpg и png, находящиеся в директории ~/test/pics. 17.07.15 Параметр —inverse говорит, что в изображениях также нужно инвертировать соответствующий цветовой канал. Примеры: --inverse r --inverse b,g --inverse r,b,g Сочетания из r,g,b могут быть любые. """ import argparse import Rotate # функция , в которой поворот и инверсия parser = argparse.ArgumentParser(description = "Turn and invert pictures with formats .jpg or .png") # сначала создаем переменную для добавления новых команд parser.add_argument("directory", help = "Folder that contains pictures") #Добавляем новый аргумент конмадной строки """ parser.add_argument("degree",type=int,default = 0, help = "What degree?") parser.add_argument("--inverse", type = str, help = "Parametrs: r - red color, g - green color, b - black color") args = parser.parse_args() #теперь это можно вводить в консоль Rotate.all_files(args.directory,args.degree,args.inverse ) # файлы формата jpg и png поворачивает на N радусов и инвертирует нужные нам каналы #принимает путь градусы и инвертируемые каналы """ #args = parser.parse_args() #ВСе вводится с командной строки стначала путь в конце не забудь \ дальше пишешь число градусов а потом --inverse "r,g,b" запомни, что это строчка и через запятые""""
jx_tot= jx.sum() / (data_sh_in_3Rfalf[:,0]*1e10).sum() jy_tot= jy.sum() / (data_sh_in_3Rfalf[:,0]*1e10).sum() jz_tot= jz.sum() / (data_sh_in_3Rfalf[:,0]*1e10).sum() jtot = np.sqrt(jx_tot**2 + jy_tot**2 + jz_tot**2) jx_tot = jx_tot/jtot jy_tot = jy_tot/jtot jz_tot = jz_tot/jtot jx=0 jy=0 jz=0 # -- compute rotation vectors: [e1,e2,e3] = Rotate.exyz(jx_tot,jy_tot,jz_tot) npar=len(data_sh[:,0]) #defino nuevas posiciones y velocidades: rot_pos = np.zeros(shape=(npar,3)) rot_vel = np.zeros(shape=(npar,3)) [rot_pos[:,0],rot_pos[:,1],rot_pos[:,2]] = Rotate.rotate(npar,data_sh[:,1],data_sh[:,2],data_sh[:,3],e1,e2,e3) [rot_vel[:,0],rot_vel[:,1],rot_vel[:,2]] = Rotate.rotate(npar,data_sh[:,4],data_sh[:,5],data_sh[:,6],e1,e2,e3) #2) Usando las nuevas posiciones y velocidades, calculamos el Krot: #Nos quedamos solo con las particulas adentro de Rgal: son = np.where(radial_pos < Rgal)[0] mass = data_sh[son,0]*1e10 rot_pos = rot_pos[son,:] rot_vel = rot_vel[son,:]
import numpy as np import Rotate import random if __name__ == '__main__': rubix_array = np.zeros([6, 9], dtype=str) # color_array = ['W','G','Y','R','B','O'] # for faces in range(0,6): # for pieces in range(0,9): # rubix_array[faces][pieces] = color_array[random.randrange(1,6)] rubix_array = [['G', 'Y', 'W', 'B', 'W', 'Y', 'B', 'R', 'W'], ['B', 'G', 'W', 'R', 'R', 'B', 'R', 'R', 'R'], ['R', 'G', 'O', 'W', 'Y', 'Y', 'B', 'O', 'Y'], ['G', 'R', 'Y', 'G', 'O', 'Y', 'G', 'W', 'Y'], ['W', 'O', 'B', 'G', 'B', 'W', 'O', 'O', 'O'], ['O', 'B', 'G', 'O', 'G', 'W', 'R', 'B', 'Y']] print("Orgial Scrambled Cube") print(rubix_array) front_face = np.reshape(rubix_array[0], (3, 3)) right_face = np.reshape(rubix_array[1], (3, 3)) back_face = np.reshape(rubix_array[2], (3, 3)) left_face = np.reshape(rubix_array[3], (3, 3)) up_face = np.reshape(rubix_array[4], (3, 3)) down_face = np.reshape(rubix_array[5], (3, 3)) # print("Face rotate anti-clockwise F'") # print(np.reshape(Rotate.front_anti_clockwise(front_face, right_face, back_face, left_face, up_face, down_face), (6, 9))) print("Face rotate clockwise F") print( np.reshape( Rotate.front_clockwise(front_face, right_face, back_face, left_face, up_face, down_face), (6, 9)))