def colour(): get_image() crop_image() img = Image.open('cropped.jpg') img2 = img.resize((1, 1), Image.ANTIALIAS) color = img2.getpixel((0, 0)) return ('#{:02x}{:02x}{:02x}'.format(*color))
def getImage(ip): if "210" in ip: movecamera = Move_Zoom(ip="192.168.2.210") for i in range(1, 8): movecamera.go_to_preset(str(i)) get_image() else: movecamera = Move_Zoom(ip="192.168.2.211") for i in range(1, 11): movecamera.go_to_preset(str(i)) get_image(CM=211)
def save_checkpoints_file(self, out_dir, n_cameras): ''' take pictures and save them in out_dir for later processing ''' choice = "y" counter = 1 while True: try: if choice == "y": for n in n_cameras: img = get.get_image(n) cv2.imwrite( '{0}/input{1}_{2}.jpg'.format(out_dir, n, counter), img) counter += 1 choice = raw_input( "Do you want to take another image? (y/n)") elif choice == "n": return counter else: choice = raw_input("Enter valid choice (y/n)") except KeyboardInterrupt: print("program terminated by user") sys.exit(1)
def get_checkpoints(self,out_dir,w,h,fisheye): ''' gets checkboard points for the intrinsic camera calibration. ''' choice = "y" counter = 1 obj_points = [] img_points = [] pattern_size = (w, h) while True: try: # Collect Data if choice == "y": img = get.get_image(self.n) h, w = img.shape[:2] img_pt, obj_pt,__ = self.get_calibpoints(img,pattern_size, counter,out_dir,fisheye) if not obj_pt == []: img_points.append(img_pt) obj_points.append(obj_pt) counter += 1 choice = input("Do you want to take another image? (y/n)") elif choice == "n": return img_points, obj_points, (w,h) else: choice = input("Enter valid choice (y/n)") except KeyboardInterrupt: print("program terminated by user") sys.exit(1)
def get_checkpoints(self,out_dir,w,h,fisheye): ''' gets checkboard points for the intrinsic camera calibration. ''' choice = "y" counter = 1 obj_points = [] img_points = [] pattern_size = (w, h) while True: try: # Collect Data if choice == "y": img = get.get_image(self.n) h, w = img.shape[:2] img_pt, obj_pt,__ = self.get_calibpoints(img,pattern_size, counter,out_dir,fisheye) if not obj_pt == []: img_points.append(img_pt) obj_points.append(obj_pt) counter += 1 choice = raw_input("Do you want to take another image? (y/n)") elif choice == "n": return img_points, obj_points, (w,h) else: choice = raw_input("Enter valid choice (y/n)") except KeyboardInterrupt: print("program terminated by user") sys.exit(1)
def draw(self): """Draws the sprite on the display according to its position and direction. """ self.skin = get_image(self.skins[self.skin_i]) rotated = pygame.transform.rotate(self.skin, self.direction) rect = rotated.get_rect() gameDisplay.blit(rotated, (self.x - stage.vp.x - rect.center[0], self.y - stage.vp.y - rect.center[1]))
def main(): credentials = pika.PlainCredentials('admin', 'swsc2018!') connection_clear = pika.BlockingConnection( pika.ConnectionParameters(host='192.168.2.93', port=5672, virtual_host='/', credentials=credentials)) channel = connection_clear.channel() p = channel.basic_get(queue='camera', auto_ack=True) while p[0]: p = channel.basic_get(queue='camera', auto_ack=True) print('清空队列') move = Move_Zoom() move.go_to_preset("8", flag=3) print('摄像头复位') while True: credentials = pika.PlainCredentials('admin', 'swsc2018!') connection = pika.BlockingConnection( pika.ConnectionParameters(host='192.168.2.93', port=5672, virtual_host='/', credentials=credentials, heartbeat=20)) channel = connection.channel() channel.basic_qos(prefetch_count=1) channel.basic_consume(on_message_callback=move, queue='camera210', auto_ack=True) try: channel.start_consuming() except Exception as e: ack_connection = pika.BlockingConnection( pika.ConnectionParameters(host='192.168.2.93', port=5672, virtual_host='/', credentials=credentials)) ack_channel = ack_connection.channel() ack_channel.basic_publish(exchange='face-exchange', routing_key='ack', body='1') ack_connection.close() get_image() continue
def setTiles(self, tiles): """Sets the background tiles. Arguments: tiles {str|list} -- either a string, a list of strings or a list of lists of strings. string - the file path to the background image list of strings - list of file paths to the background horizontal tiles list of lists - grid of the background tiles (each sublist represents a row of tiles) """ if type(tiles) is str: self.tiles = [[get_image(tiles, False)]] elif type(tiles[0]) is str: self.tiles = [[get_image(tile, False) for tile in tiles]] else: self.tiles = [[get_image(tile, False) for tile in row] for row in tiles] self.tileWidth = self.tiles[0][0].get_width() self.tileHeight = self.tiles[0][0].get_height()
def move(ch, method, properties, body): ips = str(body, encoding='utf-8') ip_list = ips.split(",") p = Pool(3) for ip in ip_list: p.apply_async(getImage, args=(ip, )) p.close() p.join() credentials = pika.PlainCredentials('admin', 'swsc2018!') ack_connection = pika.BlockingConnection( pika.ConnectionParameters(host='192.168.2.93', port=5672, virtual_host='/', credentials=credentials)) ack_channel = ack_connection.channel() ack_channel.basic_publish(exchange='face-exchange', routing_key='ack', body='1') ack_connection.close() get_image()
def get_psf(self): ''' Calculate the point spread function based on the current uv grid. The psf is normalized so that the sum is 1. Returns: * psf --- array with the same grid dimensions as uv_grid, self.get_fov() across ''' #Make a uv grid mask uv_mask = self.get_uv_grid().copy() uv_mask[self.get_uv_grid() < 1.e-15] = 0. uv_mask[self.get_uv_grid() > 1.e-15] = 1. psf = get_image.get_image(uv_mask, self.get_fov()) psf /= psf.sum() return psf
def get_image_slice(self, visibility_slice=None): ''' Calculate noise in image space. If no visibility noise has been supplied, a slice will be calculated, but not returned. Kwargs: * visibility_slice (numpy array): the visibility slice to use as input. If none, a new slice will be calculated. Returns: real array with same dimensions as uv grid, in mK ''' if visibility_slice == None: visibility_slice = self.get_visibility_slice() image = get_image.get_image(visibility_slice, self.get_fov()) return image
def __init__(self, skins, animation_fps, x, y): """Initialization. Arguments: skins {list} -- the list of the sprite's skins - taken from 'sprites.py' module animation_fps {int} -- pace (in frames per second) of the player's skin animation x {float|int} -- sprites's X-coordinate position y {float|int} -- sprite's Y-coordinate position """ pygame.sprite.Sprite.__init__(self) self.sprites.append(self) self.skins = skins self.skin = get_image(skins[0]) # Current sprite's skin self.skin_i = 0 # Index of the current sprite's skin in self.skins self.animation_fps = animation_fps self.rect = self.skin.get_rect( ) # Used in pygame.sprite class to detect collision self.x = x # Sprite's X-coordinate position self.y = y # Sprite's Y-coordinate position self.direction = 0 # Sprite's facing direction in degrees
def create_feature_matrix(label_dataframe): n_imgs = label_dataframe.shape[0] # initialized after first call to feature_matrix = None for i, img_id in tqdm(enumerate(label_dataframe.index)): features = preprocess(get_image(img_id)) # initialize the results matrix if we need to # this is so n_features can change as preprocess changes if feature_matrix is None: n_features = features.shape[0] feature_matrix = np.zeros((n_imgs, n_features), dtype=np.float32) if not features.shape[0] == n_features: print "Error on image {}".format(img_id) features = features[:n_features] feature_matrix[i, :] = features return feature_matrix
def main(): parser = argparse.ArgumentParser(description='Resize image file.') parser.add_argument('filename', type=str, help='Image to resize') parser.add_argument('res', type=float, default=1.0, help='Normalized resolution') parser.add_argument('--rename', type=bool, default=False, help='Defines whether file is renamed or not') args = parser.parse_args() image, grayscale = GI.get_image(args.filename) S = image.shape NX, NY = S[1], S[0] NY_new = int(args.res * NY) NX_new = int(args.res * NX) image = scipy.misc.imresize(image, (NY_new, NX_new)) f_new = append_to_filename_with_ext(args.filename, '_resized', args.rename) imageio.imwrite(f_new, image)
def save_checkpoints_file(self,out_dir,n_cameras): ''' take pictures and save them in out_dir for later processing ''' choice = "y" counter = 1 while True: try: if choice == "y": for n in n_cameras: img = get.get_image(n) cv2.imwrite('{0}/input{1}_{2}.jpg'.format(out_dir,n,counter),img) counter += 1 choice = raw_input("Do you want to take another image? (y/n)") elif choice == "n": return counter else: choice = raw_input("Enter valid choice (y/n)") except KeyboardInterrupt: print("program terminated by user") sys.exit(1)
def midgame_iterate(state, code_interact=False): state['counter'] += 1 if state['last_command'] != 'time_last_hit': if state['counter'] % 8 == 0 or state['last_command'] == 'retreat': center_camera_on_hero() # time.sleep(0.2) # time it takes after command to center camera image = get_image() # if state['save_counter'] == 200: # save_image(image, '100.png') # if state['counter'] % 20 = 0: # Below "A or B" means "A unless A == 0 then B instead" state['hero_damage'] = get_attack_dmg(image) or state['hero_damage'] state['levels_in_e'] = 1 #get_levels_in_e(image) state['minimap_position'] = 'todo' #get_minimap_position(image) at_t2_5 = False #is_at_t2_5(image) update_dire_creeps(state, get_dire_creeps(image, middle_area)) update_rad_creeps(state, get_radiant_creeps(image, middle_area)) # if state['hero_damage'] > 100: # show_image(image) # save_image(image, 'error.png') # code.interact(local=dict(globals(), **locals())) reposition(state, state['rad_creeps'], state['dire_creeps'], at_t2_5) gold = get_gold(image) if gold - state[ 'gold'] > 30: #melee bounty 36-40, ranged 42-48, siege 66-80 if state['lh_creeps_history'] != []: state['lh_creeps_history'][-1].last_hit_success = True state['gold'] = gold # low priority actions if state['last_command'] == 'attack': if state['gold'] > 820: buy_item('phase boots') time.sleep(0.05) toggle('f3') # if state['last_command'] == 'last_hit': # save_image(image, "last_hit_%s.png" % state['counter']) if code_interact: code.interact(local=dict(globals(), **locals()))
def midgame_iterate(state): state['counter'] += 1 if not state['quick_fire_funs'] and ( state['counter'] % 4 == 0 or state['last_command'] == 'retreat'): center_camera_on_hero() # time.sleep(0.2) # time it takes after command to center camera image = get_image() if state['quick_fire_funs']: execute_quickfire_functions(state, image) return # if state['save_counter'] == 200: # save_image(image, '100.png') # if state['counter'] % 20 = 0: state['hero_damage'] = get_attack_dmg(image) state['levels_in_e'] = get_levels_in_e(image) state['minimap_position'] = get_minimap_position(image) if state['levels_in_e'] == 4: dire_creeps = find_dire_creeps(image, middle_area) else: dire_creeps = find_dire_creeps(image, top_right_area) # if get_num_backstab_creeps(dire_creeps): # when pushing t4s/ancient # move_to_mid_t3(state) # # Can't add qf function because breaks too many unittests :( # state['quick_fire_funs'].append( # gen_retreat_quickfire(state['minimap_position'])) # # time.sleep(2) # return at_t2_5 = is_at_t2_5(image) # if not dire_creeps: # bad_iterate(state) # return # elif levels_in_e > 2 and not in_range(dire_creeps): # bad_iterate(state) # return rad_creeps = find_radiant_creeps(image, top_right_area) reposition(state, rad_creeps, dire_creeps, at_t2_5)
def generate_ppt(slides,lang='en'): prs = Presentation(random.choice(design)) filename = slides['topic']+"-"+lang + '.pptx' loc = "files/ppts/"+filename img_count=0 MyMain(slides,prs,lang) MyContent(slides,prs,lang) images=[] for d in slides["sections"]: i=0 while i<len(d['content']): MySlides(d['heading'],d['content'][i:i+4],prs,lang) i=i+4 if d['img']: try: img=get_image(d['img']) MyImage(img,prs,lang) images.append(img) os.remove(d['img']) except: pass MyExercise(prs,lang) prs.save(loc) for img in images: os.remove(img) print("ppt prepared!") print(slides) return loc
# Put camera states in their own dir csd = os.path.join( os.getcwd(), 'camera_states' ) if not os.path.exists(csd): os.makedirs(csd) failure_notifications = 0 #for index in range(0,10): while True: try: for c, camera in cameras.iteritems(): # Write jpeg to image dir and # populate camera dict with time info result = gi.get_image( ip, camera, wd, to ) if result['success']: delta_time = result['delta_time'] fname = result['fname'] # read image im = mh.imread(fname) for spot in camera['spots']: # get the polygon vertices for the spot shp_verts = spot['vertices'] # count of spectra in which car is present present = 0
data = [] for i, j in zip(np.linspace(26.575009, 26.824258, 20), np.linspace(127.981836, 128.244362, 20)): for n in np.linspace(0, 0.166134, 50): data.append([i, j + n]) for j in np.linspace(26.589016, 26.709945, 30): for i in np.linspace(127.876367, 128.037616, 30): data.append([j, i]) for i, j in zip(np.linspace(26.459480, 26.552919, 20), np.linspace(127.824643, 127.970443, 20)): for n in np.linspace(0, 0.109597, 50): data.append([i, j + n]) for i, j in zip(np.linspace(26.098296, 26.434354, 50), np.linspace(127.651460, 127.717325, 50)): for n in np.linspace(0, 0.154768, 150): data.append([i, j + n]) count = 0 #print(data[8258]) # ここで写真おとす for count, point in enumerate(data): print(count) print(point) if count >= START_COUNT: get_image.get_image(point)
def take_image(self): ''' Get image from camera''' print("Taking image from camera",self.n,"(this can take a moment)...") self.img = get.get_image(self.n)
def processCameras( cameras, dirs, to, spam=None ): for c, camera in cameras.iteritems(): # Write jpeg to image dir and # populate camera dict with time info result = gi.get_image( camera, dirs['wd'] ) if result['success']: delta_time = result['delta_time'] fname = result['fname'] # Process image ai.analyzeImage( fname, camera ) # Judging for spot in camera['spots']: present = dp.determinePresence( spot ) res = ep.evaluatePresence( spot, present, delta_time, camera['im_ts'] ) if res['message'] is not None and spam is not None: notify.send_msg_with_jpg( res['subject'], res['message'], fname, spam ) # Store all current images sfname = 'spot' + str(spot['number']) + '.jpg' cfname = os.path.join( dirs['cd'], sfname ) copyfile(fname,cfname) # Log spot data log.logSpot( camera['im_ts'], spot, dirs['sld'] ) # reset failure counter camera['nFails'] = 0 # delete the image that has been processed os.remove(fname) else: camera['nFails'] += 1 if camera['nFails'] == 5: msg = """ %s Camera %d is not producing images ! """ % (time.asctime(),camera['number']) notify.send_msg('Error',msg,to) print msg # Protect against giant seepage if camera['nFails'] > 100: camera['nFails'] = 100 # store the current state of the camera #log.addState( camera, dirs['cld'] ) log.recordState( camera, dirs['csd'] ) return
import re import os from get_image import get_image keyword = "гагарин" while not bool(keyword): keyword = input("Enter keyword: ").strip() filename = f'{re.sub(r"[^a-zA-Zа-яА-Я0-9_-]", "", keyword)}.jpeg' get_image(keyword, filename) os.system(f"open '{filename}'")
from get_image import get_image, save_image, show_image from classifiers import get_gold, get_attack_dmg, get_enemy from user_input import buy_item import time import code if __name__ == '__main__': time.sleep(0) s = time.time() bought = False counter = 0 while not bought and time.time() - s < 3: image = get_image() gold = get_enemy(image) gold = get_enemy(image) gold = get_enemy(image) gold = get_enemy(image) # print "gold:", gold dmg = get_attack_dmg(image) counter += 1 # print "damage:", dmg # if gold > 820: # buy_item('phase boots') # bought = True print counter / 3.0 print 1 / (counter / 3.0) # try: # except Exception as e: # show_image(image) # save_image(image, 'error.png')
dil_radius = 0 feature_names = [] img_format = ".png" for j in xrange(num_of_features): feature_names += ["feature_" + str(j) + img_format] num_direcs = len(training_direcs) num_channels = len(channel_names) imglist = [] for direc in training_direcs: imglist += os.listdir(os.path.join(direc_name, direc)) # Load one file to get image sizes img_temp = get_image(os.path.join(direc_name, training_direcs[0], imglist[0])) image_size_x, image_size_y = img_temp.shape # Initialize arrays for the training images and the feature masks channels = np.zeros((num_direcs, num_channels, image_size_x, image_size_y), dtype='float32') feature_mask = np.zeros( (num_direcs, num_of_features + 1, image_size_x, image_size_y)) # Load training images direc_counter = 0 for direc in training_direcs: imglist = os.listdir(os.path.join(direc_name, direc)) # print imglist channel_counter = 0 # Load channels
# Put camera states in their own dir csd = os.path.join(os.getcwd(), 'camera_states') if not os.path.exists(csd): os.makedirs(csd) failure_notifications = 0 #for index in range(0,10): while True: try: for c, camera in cameras.iteritems(): # Write jpeg to image dir and # populate camera dict with time info result = gi.get_image(ip, camera, wd, to) if result['success']: delta_time = result['delta_time'] fname = result['fname'] # read image im = mh.imread(fname) for spot in camera['spots']: # get the polygon vertices for the spot shp_verts = spot['vertices'] # count of spectra in which car is present present = 0
def main(): # with tf.Graph().as_default(): # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5) # sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) # with sess.as_default(): # pnet, rnet, onet = detection_face.create_sscnn(sess, None) with tf.Graph().as_default(): with tf.Session() as sess: model = MODEL_DIR OPSnet.load_model(model) images_placeholder = tf.get_default_graph().get_tensor_by_name( "input:0") embeddings = tf.get_default_graph().get_tensor_by_name( "embeddings:0") phase_train_placeholder = tf.get_default_graph( ).get_tensor_by_name("phase_train:0") # 人脸库匹配位置 # emb_dir = './img/emb_img' emb_dir = EMB_IMG_DIR # all_obj = [] # image = [] # nrof_images = 0 # for i in os.listdir(emb_dir): # all_obj.append(i) # img = misc.imread(os.path.join(emb_dir, i), mode='RGB') # prewhitened = OPSnet.prewhiten(img) # image.append(prewhitened) # nrof_images = nrof_images + 1 # try: # images = np.stack(image) # feed_dict = {images_placeholder: images, phase_train_placeholder: False} # compare_emb = sess.run(embeddings, feed_dict=feed_dict) # compare_num = len(compare_emb) # except: # pass credentials = pika.PlainCredentials('admin', 'swsc2018!') connection_clear = pika.BlockingConnection( pika.ConnectionParameters(host='192.168.2.93', port=5672, virtual_host='/', credentials=credentials)) clear_ack = connection_clear.channel() ack = clear_ack.basic_get(queue='ack', auto_ack=True) while ack[0]: ack = clear_ack.basic_get(queue='ack', auto_ack=True) connection_clear.close() print('清空队列') while True: print('循环识别') all_obj = [] image = [] nrof_images = 0 for i in os.listdir(emb_dir): all_obj.append(i) img = misc.imread(os.path.join(emb_dir, i), mode='RGB') prewhitened = OPSnet.prewhiten(img) image.append(prewhitened) nrof_images = nrof_images + 1 try: images = np.stack(image) feed_dict = { images_placeholder: images, phase_train_placeholder: False } compare_emb = sess.run(embeddings, feed_dict=feed_dict) compare_num = len(compare_emb) except: pass ip_list = ["192.168.2.210", "192.168.2.211"] ip_str = [] for ip in ip_list: if "210" in ip: image_path = get_image(flag=False) else: image_path = get_image(flag=False, CM=211) frame = cv2.imread(image_path) os.remove(image_path) rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) mark = load_and_align_data(rgb_frame, 160, 22) if mark: ip_str.append(ip) if ip_str: ip_str = ','.join(ip_str) credentials = pika.PlainCredentials('admin', 'swsc2018!') save_connection = pika.BlockingConnection( pika.ConnectionParameters(host='192.168.2.93', port=5672, virtual_host='/', credentials=credentials, heartbeat=20)) save_channel = save_connection.channel() save_channel.queue_declare(queue='camera', durable=True) save_channel.basic_publish(exchange='face-exchange', routing_key='images', body=ip_str) save_connection.close() else: sleep(20) continue credentials = pika.PlainCredentials('admin', 'swsc2018!') image_connection = pika.BlockingConnection( pika.ConnectionParameters(host='192.168.2.93', port=5672, virtual_host='test', credentials=credentials)) ack_connection = pika.BlockingConnection( pika.ConnectionParameters(host='192.168.2.93', port=5672, virtual_host='/', credentials=credentials)) image_channel = image_connection.channel() ack_channel = ack_connection.channel() def facedecect(ch, method, properties, body): path = str(body, encoding='utf-8') path, ip = path.split(",") print(path) frame = cv2.imread(path) os.remove(path) frame = cv2.resize(frame, (964, 540), interpolation=cv2.INTER_CUBIC) rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) mark, bounding_box, crop_image, crop_list, path_list = load_and_align_data1( rgb_frame, 160, 22) print('mark is', mark) if (mark): feed_dict = { images_placeholder: crop_image, phase_train_placeholder: False } emb = sess.run(embeddings, feed_dict=feed_dict) temp_num = len(emb) print("bbox num:", temp_num) # if face_first_flag: temp_num = len(emb) fin_obj = [] # print(all_obj) # 为bounding_box 匹配标签的到结果 score_list = [] print( "*****************************************************************************" ) for i in range(temp_num): dist_list = [] for j in range(compare_num): dist = np.sqrt( np.sum( np.square( np.subtract( emb[i, :], compare_emb[j, :])))) dist_list.append(dist) min_value = min(dist_list) if min_value > 0.66 and min_value < 0.78: fin_obj.append('pass') score_list.append(min_value) elif min_value > 0.86: fin_obj.append("pass") score_list.append(min_value) elif min_value > 0.78 and min_value < 0.86: fin_obj.append("unknown") score_list.append(min_value) else: fin_obj.append( all_obj[dist_list.index(min_value)]) score_list.append(min_value) print("min_value:", min_value) print( "*****************************************************************************" ) res = deal_name(fin_obj) print(res) print(len(crop_list), len(path_list)) for i in range(len(crop_list)): temp_dict = dict() # cv2.imshow('jpg',image_list[i]) # img_path = save_small_pic(crop_image[i]) base64_str = img_to_base64(path_list[i]) temp_dict["image"] = base64_str temp_dict["userId"] = str(res[i]) if temp_dict["userId"] == "pass": continue if temp_dict["userId"] == "unknown": continue temp_dict[ 'picName'] = '/home/ai/java/image/2019186c85d8_ee96-4951-9cd5_18c97dbbba2e.jpg' score = (1 - score_list[i]) + 0.4 temp_dict["similar"] = str(score) post_data = json.dumps(temp_dict) print(post_data) temp_dict["ip"] = ip post_data = json.dumps(temp_dict) response = requests.post( url=POST_URL_NEW, data=post_data, headers={"Content-Type": "application/json"}) print("Posted finished POST_URL_NEW1", response.json()) message = ack_channel.basic_get(queue='ack', auto_ack=True) print(message) if message[0]: image_channel.stop_consuming() ch.basic_ack(delivery_tag=method.delivery_tag) image_channel.basic_qos(prefetch_count=1) image_channel.basic_consume(on_message_callback=facedecect, queue='images') image_channel.start_consuming()
'cell8/' ] channel_names = ['nuclear'] edge_name = 'feature_0' int_name = 'feature_1' tiff_end = '.tif' png_end = '.png' num_direcs = len(training_direcs) num_channels = len(channel_names) imglist = [] for direc in training_direcs: imglist += os.listdir(direc_name + direc) # Load one file to get image sizes phase_temp = get_image(direc_name + training_direcs[0] + imglist[0]) image_size_x, image_size_y = phase_temp.shape channels = np.zeros((num_direcs, num_channels, image_size_x, image_size_y), dtype='float32') interior_mask = np.zeros((num_direcs, image_size_x, image_size_y)) exterior_mask = np.zeros((num_direcs, image_size_x, image_size_y)) edge_mask = np.zeros((num_direcs, image_size_x, image_size_y)) # Load phase images direc_counter = 0 for direc in training_direcs: print direc imglist = os.listdir(direc_name + direc) print imglist
from get_image import get_image import numpy as np import cv2 org_img, fea_img, org_gray, fea_gray = get_image() detector = cv2.ORB_create() kp1, desc1 = detector.detectAndCompute(org_gray, None) kp2, desc2 = detector.detectAndCompute(fea_gray, None) FLANN_INDEX_LSH = 6 index_params = dict(algorithm=FLANN_INDEX_LSH, table_number=6, key_size=12, multi_probe_level=1) search_params = dict(checks=32) matcher = cv2.FlannBasedMatcher(index_params, search_params) matches = matcher.match(desc1, desc2) res = cv2.drawMatches(org_img, kp1, fea_img, kp2, matches, None, flags=cv2.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS) print("Predict: ", matches[0].distance) cv2.imshow('FLANN + ORB', res) cv2.waitKey() cv2.destroyAllWindows()
import cv2 import numpy as np from get_image import get_image from Vibe import Vibe from time import time from PIL import Image path = "../data_anno/Mini61/img" cap = get_image(path) vibe = Vibe() frame = next(cap) begin = time() frame = frame.astype(np.int32) vibe.init(frame) end = time() print(end - begin) for frame in cap: frame = frame.astype(np.int32) mask = vibe.test_and_update(frame) print(mask) kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3, 3)) closed = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, kernel) cv2.imshow('mask', mask.astype(np.uint8)) cv2.imshow("closed", closed) # Image.fromarray(mask.astype(np.uint8)).show() cv2.waitKey(100)
from get_image import get_image, save_image, show_image from classifiers import get_gold import time if __name__ == '__main__': time.sleep(5) a = time.time() initial_image = get_image() old_gold = get_gold(initial_image) new_image = get_image() new_gold = get_gold(initial_image) well_behaved = True while well_behaved and time.time() - a < 40 * 60: #roll back previous values old_gold = new_gold initial_image = new_image new_image = get_image() new_gold = get_gold(new_image) print new_gold well_behaved = ((new_gold == old_gold) or (new_gold == old_gold + 1)) if not well_behaved: print "Error while counting gold" print "old: ", old_gold print "new: ", new_gold save_image(initial_image, 'gold0.png') save_image(new_image, 'gold1.png') show_image(initial_image) show_image(new_image) else: print "program well behaved"
def download_images(links): """download images from the url image get in our dictionnary from the categories list""" for link in links: book = scraping.scrap_book(link) get_image.get_image(book)