def run(self): import matplotlib matplotlib.use("Agg") import matplotlib.pylab as plt import matplotlib.animation as animation from matplotlib import cm cmap = cm.gray dpi = 100 repeat = 1 fps = 15 writer = animation.writers['ffmpeg'](fps=fps) fig = plt.figure() ax = plt.Axes(fig, [0, 0, 1, 1]) ax.set_axis_off() for input_ in self.input(): data = plt.imread(input_.path) m, n, _ = data.shape fig.set_size_inches((m / dpi, n / dpi)) break fig.add_axes(ax) with writer.saving(fig, self.output().path, dpi): for input_ in self.input(): data = plt.imread(input_.path) m, n, _ = data.shape ax.imshow(data, interpolation='none', cmap=cmap, vmin=low, vmax=high) for _ in range(repeat): writer.grab_frame()
def plot_example(filter_size): #Plot the pictuire. plt.figure(figsize=(12, 6)) plt.subplot(2, 3, 1) plt.title('Salt & pepper noise image', fontsize=10) plt.imshow(plt.imread("saltpepper.bmp"), cmap="gray") plt.subplot(2, 3, 2) plt.title('Salt & pepper noise image - local averaging', fontsize=10) plt.imshow(denoise_image("saltpepper.bmp", filter_size, "local_average"), cmap="gray") plt.subplot(2, 3, 3) plt.title('Salt & pepper noise image - median filtering', fontsize=10) plt.imshow(denoise_image("saltpepper.bmp", filter_size, "median_filter"), cmap="gray") plt.subplot(2, 3, 4) plt.title('Gaussian noise image', fontsize=10) plt.imshow(plt.imread("gaussian.bmp"), cmap="gray") plt.subplot(2, 3, 5) plt.title('Gaussian noise image - local averaging', fontsize=10) plt.imshow(denoise_image("gaussian.bmp", filter_size, "local_average"), cmap="gray") plt.subplot(2, 3, 6) plt.title('Gaussian noise image - median filtering', fontsize=10) plt.imshow(denoise_image("gaussian.bmp", filter_size, "median_filter"), cmap="gray") plt.show()
def style_transfer(content_image_path, style_image_path): try: content_image_path = "images/rnd_imgs/trump.jpg" style_image_path = "images/style_imgs/wave.jpg" content_image = plt.imread(content_image_path) style_image = plt.imread(style_image_path) content_image = content_image.astype(np.float32)[np.newaxis, ...] / 255. style_image = style_image.astype(np.float32)[np.newaxis, ...] / 255. # Optionally resize the images. It is recommended that the style image is about # 256 pixels (this size was used when training the style transfer network). # The content image can be any size. style_image = tf.image.resize(style_image, (256, 256)) hub_module = hub.load( 'https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2' ) # hub_module = hub.load("./hub_module") outputs = hub_module(tf.constant(content_image), tf.constant(style_image)) stylized_image = outputs[0] save_tensor_as_image(stylized_image) return True except Exception as e: raise e
def get_images_and_annotation(self, png_path, mask_path_list, class_names, parse_path_fn): """ parse_path_fn: function to parse class_name from path """ image = plt.imread(png_path, -1) image_3ch = np.dstack([image] * 3) masks = [] boxes = [] class_ids = [] if type(mask_path_list) == str: mask_path_list = [mask_path_list] if mask_path_list: for mask_path in mask_path_list: mask = plt.imread(mask_path, -1).astype(np.bool) # connected component analysis labeled_mask_array = measure.label(mask, connectivity=2) for i in range(np.max(labeled_mask_array)): mask = (labeled_mask_array == i + 1) masks.append(mask) box = self.get_box_from_mask(mask) boxes.append(box) class_name = parse_path_fn(mask_path) class_id = class_names.tolist().index(class_name) class_ids.append(class_id) masks = np.dstack(masks) masks = np.array(masks) boxes = np.array(boxes) class_ids = np.array(class_ids) return image_3ch, boxes, masks, class_ids
def trash(): img = plt.imread('./trash/img_0_0_5_0.png') lbl = plt.imread('./trash/lbl_0_0_5_0.png') # print(img) # plt.imshow(img, cmap='RdPu') plt.imshow(lbl, cmap='RdPu') plt.show()
def detector_batch_deploy(LogBlobDetector, inbreast_name_list): """Batch deploy blob detector Args: LogBlobDetector: inbreast_name_list: Returns: """ inbreast_dict = inbreast.generate_inbreast_dict() for name in inbreast_name_list: print(name) # get paths try: mask_path = \ list(glob.glob(os.path.join(inbreast_dict['basedir'], 'AllMASK_level2', '_combined', '{}*'.format(name))))[0] image_path = list( glob.glob( os.path.join(inbreast_dict['basedir'], 'AllPNG', '{}*'.format(name))))[0] stack_path = list( glob.glob( os.path.join(inbreast_dict['basedir'], 'stack', '{}*'.format(name))))[0] except: print('not found {}'.format(name)) continue # read images img = plt.imread(image_path, -1) img_shape = img.shape img_mask = plt.imread(mask_path, -1) img_stack = plt.imread(stack_path, -1) img_overlay = (img_stack[:, img_stack.shape[1] // 2:]) # get eroded binary mask det = LogBlobDetector(img, max_sigma=25, min_sigma=2, num_sigma=3, threshold=0.1, disk_size=50) blobs_log = det.detect() canvas = img_overlay.copy() for y, x, r in blobs_log: cv2.circle(canvas, (int(x), int(y)), int(r + 5), color=(102, 255, 0), thickness=2) # stack image side-by-side for comparison img_log = np.hstack([canvas, np.dstack([img] * 3)]) plt.imsave( os.path.join(inbreast_dict['basedir'], 'log', '{}_log_th0.1.png'.format(name)), img_log)
def makeRowHistoIntersection(totalFrames, f_name): """ the function takes in a parameter for the total number of frames, calculates image height and width from the first frame, makes a 3 dimensional array with dimensions (width, totalFrames, 3) these are the dimensions for the STI, chromatizes the entire frame row by row, makes histograms and calculates their difference and stores it to make an STI. """ #calculating height and width imag = Image.open(f_name + "/frm0.jpg") width = imag.width height = imag.height #making a 3d array to represent STI lum_img = [] for a in range(height): lum_img.append([]) for b in range(totalFrames): lum_img[a].append([]) for c in range(3): lum_img[a][b].append(0) #nested while loops to go over every pixel in every row in every frame i = 0 #loop to go over every frame while (i < totalFrames - 1): #taking in two frames at a time to calculate #histogram difference betwween time t and t-1 img1 = plt.imread(f_name + "/frm" + str(i) + ".jpg") img2 = plt.imread(f_name + "/frm" + str(i + 1) + ".jpg") #chromatizing the frame chromatImg1 = colourToChromaticity(img1, f_name) chromatImg2 = colourToChromaticity(img2, f_name) j = 0 k = 0 #lists to store pixel data from chromatized rows row1 = [0] * width row2 = [0] * width #nested loops for going over all pixels in rows and columns while (j < height): k = 0 while (k < width): row1[k] = chromatImg1[j][k] row2[k] = chromatImg2[j][k] k = k + 1 #making histograms from columns histo1 = makeHistogram(row1, f_name) histo2 = makeHistogram(row2, f_name) #calculating the histogram difference and making STI lum_img[j][i][0] = histogramDiff(histo1, histo2) j = j + 1 i = i + 1 return np.array(lum_img)
def main(): data_filenames = sorted(os.listdir(data_dir)) img_filenames = data_filenames[0::2] seg_filenames = data_filenames[1::2] for img_filename, seg_filename in zip(img_filenames, seg_filenames): img = plt.imread(data_dir + '/' + img_filename) seg = plt.imread(data_dir + '/' + seg_filename) rmin, rmax, cmin, cmax = bbox(seg) imsave(cropped_data_dir + img_filename, img[rmin:rmax + 1, cmin:cmax + 1])
def load_ground_truth_data(base_path: Union[None, Path, str] = None): if base_path is None: base_path = Path(__file__).parents[1].joinpath('webapp', 'data') else: base_path = Path(base_path) images_ids = sorted(p.stem for p in base_path.iterdir() if p.is_file() and not p.stem.endswith('_gt')) images = [] ground_truths = [] for img_id in images_ids: img_name = str(base_path.joinpath(f'{img_id}.png')) gt_name = str(base_path.joinpath(f'{img_id}_gt.png')) # Read image to segment try: img_data = plt.imread(img_name) if np.amax(img_data) <= 1: log.debug( f'Image {img_id}.png value range was converted from [0, 1] to [0, 255]' ) img_data *= 255 img_data = img_data.astype(np.uint8, copy=False) except FileNotFoundError: log.warning(f'Skipping since no file found with name {img_name}') images.append(None) ground_truths.append(None) continue if 2 < img_data.ndim: img_data = np.rint( ImageTools.rgb_to_grayscale(img_data.astype( np.float64))).astype(np.uint8) assert np.amax(img_data) > 1 images.append(img_data) # Read GT image gt_data = plt.imread(gt_name) if gt_data.ndim == 3: gt_data = gt_data[:, :, 0] ground_truths.append(gt_data > 0) return { img_id: (img, gt) for img_id, img, gt in zip(images_ids, images, ground_truths) if img is not None }
def make_batch(self, batch_size, img_ids=None): if img_ids: pass else: # imageをランダムで選ぶ. choice = list(range(len(self.coco.dataset["images"]))) random.shuffle(choice) # 無作為にimg_idを選ぶ. img_ids = [self.coco.dataset["images"][c]["id"] for c in choice[:batch_size]] images = self.coco.loadImgs(img_ids) images = [plt.imread(os.path.join(self.IMG_DIR, image["file_name"])) for image in images] images = [image if image.ndim == 3 else np.tile(np.expand_dims(image, axis=-1), 3) for image in images] anno_ids = [self.coco.getAnnIds(img_id) for img_id in img_ids] annos_batch = [self.coco.loadAnns(anno_id) for anno_id in anno_ids] # 追加 #gt_boxes = [b if len(b) else np.zeros((1, 4)) for b in gt_boxes] #gt_masks = [[self.coco.annToMask(anno)[int(gt_boxes[i][j][0]):int(gt_boxes[i][j][2]), int(gt_boxes[i][j][1]):int(gt_boxes[i][j][3])] for j, anno in enumerate(annos)] for i, annos in enumerate(annos_batch)] gt_masks = [[self.coco.annToMask(anno) for j, anno in enumerate(annos)] for i, annos in enumerate(annos_batch)] gt_masks = [np.array(m) for m in gt_masks] gt_masks = [m if m.size else np.empty((0,) + im.shape[:2]) for m, im in zip(gt_masks, images)] gt_boxes_old = [[anno["bbox"] for anno in annos] for annos in annos_batch] gt_boxes_old = [np.array(b) for b in gt_boxes_old] gt_boxes_old = [b if b.size else np.empty((0, 4)) for b in gt_boxes_old] gt_boxes_old = convert_boxes(gt_boxes_old) gt_boxes = [[make_gt_box_from_mask(m) for m in gt_mask] for gt_mask in gt_masks] gt_boxes = [np.array(b) for b in gt_boxes] gt_boxes = [b if b.size else np.empty((0, 4)) for b in gt_boxes] #gt_boxes = [m if len(m) else np.zeros((1,) + im.shape[:2]) for m, im in zip(gt_masks, images)] gt_class_ids = [[anno["category_id"] for anno in annos] for annos in annos_batch] gt_class_ids = [[self.cls_ids[i] for i in gt_class_id] for gt_class_id in gt_class_ids] gt_class_ids = [np.array(ids) for ids in gt_class_ids] gt_class_ids = [ids if ids.size else np.empty((0,)) for ids in gt_class_ids] #gt_class_ids = [ids if ids.size else np.zeros((1,)) for ids in gt_class_ids] return images, gt_boxes, gt_masks, gt_class_ids, img_ids
def main(): A = np.mat(readPic()).transpose() acc_num = 0 for i in range(1, 13): picNum = i test_img = plt.imread("feret/%d-6.bmp" % (picNum)) b = np.mat(test_img.flatten().reshape(112 * 92, 1)) x = np.mat(np.zeros(shape=(600, 1))) L = np.linalg.norm(A, 2)**2 Lambda = 0.1 threshold = np.inf k = 0 while threshold > 2000000: z = x - 1 / L * (A.T * (A * x - b)) x = argminX(L, Lambda, z) threshold = sum((np.dot(A, x) - b).transpose() * (np.dot(A, x) - b)) + Lambda * sum(abs(x)) k += 1 if k > 2000: break index = predict_class(x) + 1 print("predicting the 6-th pic from person:", picNum) print("prediction:", index) if index == picNum: acc_num += 1 print("accuracy:", 67 / 0.7)
def __getitem__(self, index): # set path ima_name = self.list_names[index] + '.jpg' img_path = os.path.join(self.path_images, ima_name) ima_name = self.list_names[index] + '.png' sal_path = os.path.join(self.path_saliency, ima_name) fixations_path = os.path.join(self.path_fixations, self.list_names[index] + '.mat') all_dt = {} if 'caffe_img' in self.type: cf_img = read_caffe_img(img_path, self.size[self.type.index('caffe_img')]) all_dt['caffe_img'] = cf_img if 'vgg_img' in self.type: vgg_img = read_vgg_img(img_path, self.size[self.type.index('vgg_img')]) all_dt['vgg_img'] = vgg_img if 'sal_img' in self.type: sal_img = read_saliency(sal_path, self.size[self.type.index('sal_img')]) all_dt['sal_img'] = sal_img / 255.0 if 'fixation' in self.type: fixation = read_fixation(fixations_path, self.size[self.type.index('fixation')]) #print(len(fixation)) all_dt['fixation'] = fixation if 'fixation_path' in self.type: all_dt['fixation_path'] = fixations_path if 'scipy_img' in self.type: scipy_img = plt.imread(img_path) all_dt['scipy_img'] = scipy_img #print(cf_img.shape, vgg_img.shape, sal_img.shape, fixation.shape) return all_dt
def test_gaussian_filter(imgname, filter_shape, std): fd1 = filter_shape[0] fd2 = filter_shape[1] if fd1 <= 3 or fd2 <= 3: raise Exception("invalid gaussian filter.") x = np.arange( fd1) # about to generate samples in x. Make sure they are all positive y = np.arange(fd2) mean_x = np.mean(x) # get the value of the discrete values mean_y = np.mean(y) if fd1 % 2 == 0 or fd2 % 2 == 0: # if it is even raise Exception( "i don't want to support even gaussian for computation sake") width1 = fd1 * std width2 = fd2 * std sample_x = np.linspace(mean_x - ((fd1 - 1) / 2), mean_x + ((fd1 - 1) / 2), num=fd1) sample_y = np.linspace(mean_y - ((fd2 - 1) / 2), mean_x + ((fd2 - 1) / 2), num=fd2) gaussian1d_x = np.exp( (-(sample_x - mean_x)**2) / (2.0 * std**2)) # feed gaussian function the sample points min_gaussian_x = np.min(gaussian1d_x) gaussian1d_x = gaussian1d_x / min_gaussian_x # normalize it so the smallest entry is 1 gaussian1d_x = np.floor(gaussian1d_x) # round the nearest integer gaussian1d_y = np.exp((-(sample_y - mean_y)**2) / (2.0 * std**2)) min_gaussian_y = np.min(gaussian1d_y) gaussian1d_y = gaussian1d_y / min_gaussian_y gaussian1d_y = np.floor(gaussian1d_y) im = plt.imread(imgname) filter_shape = gaussian1d_x.shape image_shape = im.shape imnew = copy.deepcopy(im) ## # gaussian1d_x=gaussian1d_y=np.array([1,9,18,9,1]) ## gaussian1d_x = gaussian1d_x / (np.sum(gaussian1d_x) ) # normalize by the sum gaussian1d_y = gaussian1d_y / (np.sum(gaussian1d_y)) for c in range(image_shape[1]): imnew[c, :] = np.convolve(imnew[c, :], gaussian1d_y, 'same') for r in range(image_shape[0]): imnew[:, r] = np.convolve(imnew[:, r], gaussian1d_x, 'same') print(gaussian1d_x) return (im, imnew)
def texturing(): # my_model = torch.load("Results/model.pt") picture = plt.imread("./Data/sjors2.jpg")[:, :, :3] # landmarks_3d = ? # alpha, delta = my_model.alpha.item(), my_model.delta.item() # w1, w2, w3 = model.omega[0].item(), model.omega[1].item(), model.omega[2].item() # t1, t2, t3 = model.tau[0].item(), model.tau[1].item(), model.tau[2].item() # these values are taken from main 4 alpha, delta = 0.01611, -0.02186 w1, w2, w3 = -4.20758, -2.91587, -1.17026 t1, t2, t3 = 13.58724, -15.46050, -513.25446 t = np.array([t1, t2, t3]).reshape(3, 1) omega = np.array([w1, w2, w3]) bfm = h5py.File("Data/model2017-1_face12_nomouth.h5", 'r') pca_model = MyPCAModel(bfm, 30, 20) # maybe some other value G = pca_model.generate_point_cloud(alpha, delta) p_G = get_projection(G, omega, t) # plot point cloud mean_tex = bilinear_interpolation(p_G, picture) triangles = np.asarray(bfm['shape/representer/cells'], dtype=np.int32).T mesh = Mesh(G, mean_tex, triangles) mesh_to_png("Results/george.png", mesh)
def InsertIntoNpArray(fileCount, photos): for i in range(1, fileCount + 1): # print("file"+str(i)+".png") im = plt.imread("Resize_file" + str(i) + ".png") print(type(im)) print(im.shape) photos[i] = im
def load_per_data_purpose(data_root_path, shape_in, purpose, verbose=False): entry = (0,) + shape_in x_tgt = np.empty(entry, dtype='uint8') y_tgt = np.empty((0,), dtype='uint8') if verbose: print("Loading per data purpose: ",purpose) for ct in range(0,len(categories)): path_list = populate_path_list(data_root_path + "/" + purpose + "/" + categories[ct]) n_images = len(path_list) # n_images = 5 # TODO - test only! curr_entry = (n_images,) + shape_in curr_x = np.empty(curr_entry, dtype='uint8') if verbose: print("Loading images from category ",categories[ct]) for img in range(0, n_images): if verbose: print(str(img) + "\t", end='') if img != 0 and (img % 25) == 0: print("") try: curr_x[img] = np.resize(plt.imread(path_list[img]), shape_in) except ValueError: # traceback.print_exc() print("ValueError: Error image path: " + path_list[img], file=sys.stderr) curr_y = np.empty((n_images), dtype='uint8') curr_y.fill(ct) y_tgt = np.append(y_tgt, curr_y) x_tgt = np.concatenate((x_tgt, curr_x), axis=0) return x_tgt, y_tgt
def image_processing(images): n_images = len(images) mat = np.zeros(shape=(n_images, 3, 71, 71)) for idx, img in enumerate(images): img = plt.imread(img).T mat[idx] = img return mat
def makeRowSTI(totalFrames, f_name): """ the function takes in a parameter for the total number of frames, calculates image height and width from the first frame, makes a 3 dimensional array with dimensions (width, totalFrames, 3) these are the dimensions for the row STI, then, using a loop to access all the frames and another loop within it to process each pixel in the middle row of each frame and then assign these pixels to the ith column representing the current frame being processed. """ #calculating height and width lum_img = [] #STI imag = Image.open(f_name + "/frm1.jpg") width = imag.width height = imag.height #making a 3d array to represent STI for a in range(width): lum_img.append([]) for b in range(totalFrames): lum_img[a].append([]) for c in range(3): lum_img[a][b].append(0) #nested loop to process pixels from the middle row of each frame i = 0 while (i < totalFrames): img = plt.imread(f_name + "/frm" + str(i) + ".jpg") j = 0 while (j < width): lum_img[j][i] = img[int(height / 2)][j] j = j + 1 i = i + 1 #returning the STI return np.array(lum_img)
def thread_work(sblst_sub): imgs = [] imgpath = [] for pic_name in sblst_sub: try: filepath_src = src_dir + '/' + lst[ind] + '/' + pic_name if pic_name.endswith('.db') == True: continue else: # 'images' should be either a 4D numpy array of shape (N, height, width, channels) # or a list of 3D numpy arrays, each having shape (height, width, channels). # Grayscale images must have shape (height, width, 1) each. # All images must have numpy's dtype uint8. Values are expected to be in # range 0-255. img = plt.imread(filepath_src) for ten_times_cnt in range(0, 9): imgs.append(img) imgpath.append(src_dir + '/' + lst[ind] + '/' + 'aug' + str(ten_times_cnt) + pic_name) except (IOError), e: print e continue else: continue
def make_label(image_path, anno_path): image = plt.imread(image_path) #Read the Image image_size = image.shape #Size/Dimensions of Image shape = image_size[:-1] mat_data = loadmat(anno_path)['anno'][0, 0] #.mat Annotation file image_name = mat_data['imname'][0] n_objects = mat_data['objects'].shape[1] flag = 0 for obj in mat_data['objects'][0, :]: if obj['parts'].shape[1] > 0 and ('lhand' in obj['parts'][0,:]['part_name'] or 'rhand' in obj['parts'][0,:]['part_name']): #We are only interested in Person-Parts! flag += 1 mask = obj['mask'] props = regionprops(mask)[0] class_name = obj['class'][0] class_ind = obj['class_ind'][0, 0] part_mask = np.zeros(shape, dtype=np.uint8) n_parts = obj['parts'].shape[1] if n_parts > 0: for part in obj['parts'][0, :]: part_name = part['part_name'][0] pid = MAP[class_ind][part_name] part_mask[part['mask'] > 0] = pid if flag != 0: return image_size, part_mask else: return 0, 0
def calibrate_division_model_test(): img = rgb2gray(plt.imread('test/kamera2.png')) y0 = np.array(img.shape)[::-1][np.newaxis].T / 2. z_n = np.linalg.norm(np.array(img.shape) / 2.) points = pilab_annotate_load('test/kamera2_lines.xml') points_per_line = 5 num_lines = points.shape[0] / points_per_line lines_coords = np.array([ points[i * points_per_line:i * points_per_line + points_per_line] for i in xrange(num_lines) ]) c = camera.calibrate_division_model(lines_coords, y0, z_n) import matplotlib.cm as cm plt.figure() plt.imshow(img, cmap=cm.gray) for line in xrange(num_lines): x = lines_coords[line, :, 0] plt.plot(x, lines_coords[line, :, 1], 'g') mc = camera.fit_line(lines_coords[line].T) plt.plot(x, mc[0] * x + mc[1], 'y') xy = c.undistort(lines_coords[line].T) plt.plot(xy[0, :], xy[1, :], 'r') plt.show() plt.close()
def __getitem__(self, index): ima_name = self.list_names[index] + '.jpeg' img_path = os.path.join(self.path_images, ima_name) sal_name = self.list_names[index] + '_fixMap.jpg' sal_path = os.path.join( self.path_images.replace('ALLSTIMULI', 'ALLFIXATIONMAPS'), sal_name) pts_name = self.list_names[index] + '_fixPts.jpg' pts_path = os.path.join( self.path_images.replace('ALLSTIMULI', 'ALLFIXATIONMAPS'), pts_name) all_dt = {} if 'sal_img' in self.type: sal = read_saliency(sal_path, self.size[self.type.index('sal_img')]) all_dt['sal_img'] = sal / 255.0 if 'fixation' in self.type: pts = read_saliency(pts_path, self.size[self.type.index('fixation')]) all_dt['fixation'] = pts / 255.0 if 'caffe_img' in self.type: cf_img = read_caffe_img(img_path, self.size[self.type.index('caffe_img')]) all_dt['caffe_img'] = cf_img if 'vgg_img' in self.type: #print('!!!!', self.type.index('vgg_img'), self.size) vgg_img = read_vgg_img(img_path, self.size[self.type.index('vgg_img')]) #print(vgg_img[0].shape) all_dt['vgg_img'] = vgg_img if 'scipy_img' in self.type: scipy_img = plt.imread(img_path) all_dt['scipy_img'] = scipy_img return all_dt
def mapPoints(lats,lngs,args_corrected=False,args_center=[0,0],args_width=640,args_hight=640,args_zoom=17,args_scale=2): global zoom,scale,lat,lng,w,h; #this part handles arguments to the function and correction of coordinates w=args_width; h=args_hight; zoom=args_zoom; scale=args_scale; lat=args_center[0]; lng=args_center[1]; if scale>2: print('scale is too high, a maximum value of 2 will be used.'); scale=2; if args_center[0]==0 and args_center[1]==0: print('no center coordinate was use, the default of (0.0,0.0) will be used.') if not args_corrected: lats_corrected=[]; lngs_corrected=[]; for i in range(0,len(lats)): x,y=reverse_getPointLatLng(lats[i],lngs[i]); lats_corrected.append(x); lngs_corrected.append(y); else: lats_corrected=lats; lngs_corrected=lngs; ## this part is for plotting the data over an image query="http://maps.googleapis.com/maps/api/staticmap?center="+str(lat)+","+str(lng)+"&zoom="+str(zoom)+"&size="+str(w)+"x"+str(h)+"&scale="+str(scale)+"&maptype=roadmap" pic=urllib.request.urlretrieve(query, "tmp.png") pic=plt.imread('tmp.png') plt.figure(figsize=(15,15)) plt.imshow(pic) plt.plot(lats_corrected,lngs_corrected,'.') plt.xlim([0,scale*640]); mapplot=plt.ylim([scale*640,6]); return mapplot;
def visualize_image(image_file, box_list, image_scale=2, y_vp=None, vp_color=(0, 255, 0), box_color=(255, 255, 0)): """ Args: image_file: box_list: image_scale: y_vp: y coordinate of the vanishing point/line Returns: """ img = plt.imread(image_file, -1) img = cv2.resize(img, (0, 0), fx=image_scale, fy=image_scale) width = img.shape[1] if len(img.shape) == 3 and img.shape[2] > 3: img = img[..., :3].astype(np.uint8) if y_vp is not None: img = cv2.line(img, (0, y_vp), (width - 1, y_vp), color=vp_color, thickness=10) plt.figure() plt.imshow(img) img = get_bbox_on_canvas(img, box_list, color=box_color) if y_vp is not None: img = cv2.line(img, (0, y_vp), (width - 1, y_vp), color=vp_color, thickness=10) plt.figure() plt.imshow(img)
def make_input(filename, xcenters, ycenters, shape_x=IMG_WIDTH, shape_y=IMG_HEIGHT, cutoff_y=1600): width = 3384 height = 2710 padding_x = width // 6 img = np.zeros((height, width + padding_x * 2, 3), dtype='float32') img[:, padding_x:-padding_x, :] = plt.imread(filename).astype( 'float32') / 255 mask = np.zeros((img.shape[0], img.shape[1], 1), dtype='float32') output = np.zeros((img.shape[0], img.shape[1], 3), dtype='float32') input_tensor = np.concatenate([img, mask], axis=2) input_tensor, output = input_tensor[cutoff_y:], output[cutoff_y:] input_tensor = cv2.resize(input_tensor, (shape_x, shape_y)) for xcenter, ycenter in zip(xcenters, ycenters): xcenter = xcenter * width ycenter = ycenter * height if xcenter < -padding_x or xcenter > width + padding_x or ycenter < 0 or ycenter > height: # print('f**k') # if result is too ridiculous continue xcenter = (xcenter + padding_x) / (width + padding_x * 2) * shape_x ycenter = (ycenter - cutoff_y) / (height - cutoff_y) * shape_y input_tensor[int(ycenter), int(xcenter), 3] = 1 return input_tensor.astype('float32').transpose((2, 0, 1))
def sube_imagen(dire): cargo = Image.open(dire) b_n = cargo.convert('L') b_n.save('ima.png') #Subo nueva imagen a blanco y negro para obtener el array imab_n = plt.imread('ima.png') return imab_n
def __getitem__(self, index): ima_name = self.list_names[index] + '.jpg' img_path = os.path.join(self.path_images, ima_name) all_dt = {} if 'deepgaze2_img' in self.type: img_name = self.list_names[index] + '.png' deep_gaze_img = os.path.join(self.pseudo_gt_path, img_name) deep_gaze_pred = read_saliency(deep_gaze_img, self.size) all_dt['deepgaze2_img'] = deep_gaze_pred if 'npy_img' in self.type: img_name = self.list_names[index] + '.npy' npy_img = os.path.join(self.pseudo_gt_path, img_name) npy_dt = np.load(npy_img) npy_dt = resize_interpolate(npy_dt, self.size) all_dt['npy_img'] = npy_dt if 'caffe_img' in self.type: cf_img = read_caffe_img(img_path, self.size) all_dt['caffe_img'] = cf_img if 'vgg_img' in self.type: vgg_img = read_vgg_img(img_path, self.size) all_dt['vgg_img'] = vgg_img if 'scipy_img' in self.type: scipy_img = plt.imread(img_path) all_dt['scipy_img'] = scipy_img return all_dt
def __getitem__(self, index): #print(self.list_names[0]) ima_name = self.list_names[index] if self.mode == 'test': img_path = os.path.join(self.path_images, ima_name+'.png') else: img_path = os.path.join(self.path_images, ima_name[1:]) sal_name = ima_name.split('/') sal_path = os.path.join(self.path_annotation, sal_name[0]+'/maps/'+sal_name[1]) pts_path = os.path.join(self.path_annotation, sal_name[0]+'/fixation/'+sal_name[1]) all_dt = {} if 'caffe_img' in self.type: #print(img_path) cf_img = read_caffe_img(img_path, self.size[self.type.index('caffe_img')]) all_dt['caffe_img'] = cf_img if 'vgg_img' in self.type: vgg_img = read_vgg_img(img_path, self.size[self.type.index('vgg_img')]) all_dt['vgg_img'] = vgg_img if 'sal_img' in self.type: sal_img = read_saliency(sal_path, self.size[self.type.index('sal_img')]) all_dt['sal_img'] = sal_img if 'fixation' in self.type: fixation = plt.imread(pts_path) all_dt['fixation'] = fixation if 'fixation_path' in self.type: all_dt['fixation_path'] = pts_path return all_dt
def load_image(image, image_size=(256, 256), preserve_aspect_ratio=True): img = plt.imread(image).astype(np.float64)[np.newaxis, ...] if img.max() > 1.0: img = img / 255. if len(img.shape) == 3: img = tf.stack([img, img, img], axis=-1) img = tf.image.resize(img, image_size, preserve_aspect_ratio=True) return img
def readPic(): A = [] for i in range(1, 121): for j in range(1, 6): picName = str(i) + '-' + str(j) img = plt.imread("feret/%s.bmp" % (picName)) A.append(img.flatten()) return A
def draw_next(self): try: self.curr_idx, self.curr_image = self.im_generator.next() except StopIteration: plt.close() return plt.title('%s, %d / %d' % (self.path, self.curr_idx + 1, len(self.files))) self.ax.imshow(plt.imread(self.curr_image)) self.fig.canvas.draw()
def enhance(input_file, output_file, stdval=6.0, just_alpha=False): if just_alpha: im = pl.imread(input_file)[:,:,:3] nim = na.zeros_like(im) nz = im[im>0.0] nim = im/(nz.mean()+stdval*na.std(nz)) nim[nim>1.0]=1.0 nim[nim<0.0]=0.0 write_bitmap(nim, output_file) del im, nim, nz else: im = pl.imread(input_file)[:,:,:3] nim = na.zeros_like(im) for c in range(3): nz = im[:,:,c][im[:,:,c]>0.0] nim[:,:,c] = im[:,:,c]/(nz.mean()+stdval*na.std(nz)) del nz nim[:,:][nim>1.0]=1.0 nim[:,:][nim<0.0]=0.0 write_bitmap(nim, output_file) del im, nim
def test_get_correspondences(): import matplotlib.pylab as plt import numpy as np pto = huginpto.HuginPto('test/kamera1-8.pto') img = plt.imread('test/kamera2.png') plt.imshow(img) print pto.get_available_correspondence_pairs() c0, c1 = pto.get_correspondences(0, 1) c0 = np.array(c0) c1 = np.array(c1) plt.plot(c1[:, 0], c1[:, 1], '+') plt.show()
def load_test(): c = camera.Camera(1) c.load('test/camera_01.yaml') # pitch dimensions [-20, -10, 19, 9.5] # xmin, ymin, xmax, ymax points = np.array([[-20, -10, 0], [-20, 9.5, 0], [19, 9.5, 0], [19, -10, 0], [-20, -10, 0]]).T c.plot_world_points(points, 'r-', solve_visibility=False) points = np.array([[0, -10, 0], [0, 9.5, 0]]).T c.plot_world_points(points, 'y-', solve_visibility=False) import matplotlib.pylab as plt plt.imshow(plt.imread('test/cam01.png')) # plt.show() plt.savefig('camera_load_test.png', dpi=150)
def run_fix(ld = 2, u = 8, Q1 = 0.05, Q2 = 0.1, img = ''): if not img: img = plt.imread('test/Sublime_text.png') else: img = plt.imread(img) if img.max() >= 200: img /= 255.0 #plt.figure() #plt.imshow(img) #plt.figure() new = np.zeros(img.shape) for i in range(img.shape[2]): new[:, :, i] = fix_image(img[:, :, i], ld, u, Q1, Q2) #plt.imshow(new) filename = generate_random_file_name() plt.imsave('static/temp/' + filename, new) return 'static/temp/' + filename
def show_path(self, start, goal, came_from, img_high=None, scale=1, save=False): if not img_high: img_high = self.figname fig2 = pylab.imread(img_high) current = goal while not current == start: x, y = current x *= scale y *= scale fig2[y][x] = np.array([255, 0, 0], dtype=np.uint8) current = came_from[current] pylab.imshow(fig2) if save: pylab.imsave(arr=fig2, fname=img_high[:-4]+'_minpath.png')
def load_images(directory, ext): """ This method loads all images with a particular extension from the indicated directory. PARAMETERS: directory - A string containing the appropriate directory. ext - The desired file extension. For example '.jpg'. RETURNS images - A list of images represented as numpy arrays. """ files = [f for f in os.listdir(directory) if f.endswith(ext)] images = [] for i in range(len(files)): images.append(pylab.imread(directory + files[i])) return images
def calibrate_division_model_test(): img = rgb2gray(plt.imread('test/kamera2.png')) y0 = np.array(img.shape)[::-1][np.newaxis].T / 2. z_n = np.linalg.norm(np.array(img.shape) / 2.) points = pilab_annotate_load('test/kamera2_lines.xml') points_per_line = 5 num_lines = points.shape[0] / points_per_line lines_coords = np.array([points[i * points_per_line:i * points_per_line + points_per_line] for i in xrange(num_lines)]) c = camera.calibrate_division_model(lines_coords, y0, z_n) import matplotlib.cm as cm plt.figure() plt.imshow(img, cmap=cm.gray) for line in xrange(num_lines): x = lines_coords[line, :, 0] plt.plot(x, lines_coords[line, :, 1], 'g') mc = camera.fit_line(lines_coords[line].T) plt.plot(x, mc[0] * x + mc[1], 'y') xy = c.undistort(lines_coords[line].T) plt.plot(xy[0, :], xy[1, :], 'r') plt.show() plt.close()
#!/usr/bin/env python import os, sys basedir = os.path.abspath(os.path.dirname(__file__)) libdir = os.path.abspath(os.path.join(basedir, '../lib')); libtest = os.path.abspath(os.path.join(basedir, '../lib/test')); sys.path.append(libdir) sys.path.append(libtest) import matplotlib.pylab as plt fname = sys.argv[1] #plt.figure() img = plt.imread(fname) fig, ax = plt.subplots() im = ax.imshow(img) plt.show()
def __init__(self, image_filename): self.figname = image_filename self.fig = pylab.imread(image_filename) h, w = len(self.fig), len(self.fig[0]) super().__init__(w, h) self._find_walls()
import cv2 import matplotlib.pylab as plt from pyzernikemoment import Zernikemoment if __name__ == '__main__': n = 4 m = 2 print '------------------------------------------------' print 'Calculating Zernike moments ..., n = %d, m = %d' % (n, m) fig, axes = plt.subplots(2, 3) imgs = ['Oval_H.png', 'Oval_45.png', 'Oval_V.png'] for i in xrange(3): src = cv2.imread(imgs[i], cv2.IMREAD_COLOR) src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) Z, A, Phi = Zernikemoment(src, n, m) axes[0, i].imshow(plt.imread(imgs[i])) axes[0, i].axis('off') title = 'A = ' + str(round(A, 4)) + '\nPhi = ' + str(round(Phi, 4)) axes[0, i].set_title(title) imgs = ['Shape_0.png', 'Shape_90.png', 'Rectangular_H.png'] for i in xrange(3): src = cv2.imread(imgs[i], cv2.IMREAD_COLOR) src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) Z, A, Phi = Zernikemoment(src, n, m) axes[1, i].imshow(plt.imread(imgs[i])) axes[1, i].axis('off') title = 'A = ' + str(round(A, 4)) + '\nPhi = ' + str(round(Phi, 4)) axes[1, i].set_title(title) print 'Calculation is complete'
try: import pyfits except ImportError: try: from astropy.io import fits as pyfits except ImportError: raise ImportError("Cannot import either pyfits or astropy.io.fits") import math from math import exp from matplotlib.pylab import imread from numpy.oldnumeric.functions import zeros, ravel I=imread('3.png') I=I[:,:,:3] (h,w,planes) = I.shape XY = pyfits.open('16b.fits')[1].data X = XY.field('X') Y = XY.field('Y') psfw = 1.0 stars = zeros((h,w)).astype(float) for (x,y) in zip(X,Y): ix = int(round(x)) iy = int(round(y)) for dy in range(-5, 6): yy = iy + dy if yy < 0 or yy >= h: continue for dx in range(-5, 6): xx = ix + dx
print('#' if p > 1 else '.', end='') print('') def save_fig(fig, min_path, width, name='minpath.bmp'): for p in min_path: i, j = div(p, width) fig[i][j] = np.array([255, 0, 0], dtype=np.uint8) pylab.imshow(fig) # fig = pylab.imread('beta.bmp') fig = pylab.imread('beta_3x4.bmp') # fig = pylab.imread('beta_75x100.bmp') height, width = len(fig), len(fig[0]) matrix = np.ones((height, width), dtype=int) # Converts the image into a matrix # Anything darker than medium grey will be a "wall" # The rest is "walkable" area for i in range(height): for j in range(width): matrix[i][j] = int(99) if fig[i][j][0] < 128 else 1 # Set-up all the edges edges = list() for i in range(height):
def extract_features(image_path_list): ''' This function takes a list of image paths and computes several features of each image in order to classify them. This include both basic properties like size and aspect ratio as well as doing object recognition and counting. This runs at about 1/s/core on a quad-core with HT 2.93 GHz i7. ''' feature_list = [] name_list = [] file_list = [] #iterate through all the image paths for image_path in image_path_list: image_array = imread(image_path) feature = [] feature.append(image_array.size) shape = image_array.shape #check if the image isblack or white if len(shape) > 2: feature.append(1) #convert color images to grey so they can be compared with greyscale ones image_array = color.rgb2grey(image_array) ''' # Can't use these because there is nothing comparable for black and # white images feature.append(sum(sum(image_array[:,:,0]))) feature.append(sum(sum(image_array[:,:,1]))) feature.append(sum(sum(image_array[:,:,2]))) hsv = color.rgb2hsv(img_as_float(image_array)) feature.append(sum(sum(hsv[:,:,0]))) feature.append(sum(sum(hsv[:,:,1]))) feature.append(sum(sum(hsv[:,:,2]))) ''' else: feature.append(0) #print "bw: ", image_path #determine basic image shape properties feature.append(shape[0]) feature.append(shape[1]) feature.append(shape[0]/shape[1]) #compute the amount of different shades of grey and their ratios black = np.average(image_array.flat <= 0.25 ) darkgrey = np.average((image_array.flat > 0.25) & (image_array.flat <= 0.5)) lightgrey = np.average((image_array.flat > 0.5) & (image_array.flat <= 0.75)) white = np.average(image_array.flat > 0.75) feature.append(black) feature.append(darkgrey) feature.append(lightgrey) feature.append(white) feature.append(black/(white+1)) feature.append(lightgrey/(darkgrey+1)) feature.append(lightgrey/(black+1)) # compute the average of several common filter outputs feature.append(np.average(flt.sobel(image_array))) feature.append(np.average(ndimage.morphological_gradient(image_array, size=(2,2)))) feature.append(np.average(flt.prewitt(image_array))) feature.append(np.average(flt.canny(image_array))) #Use the canny filter to delineate object and then count the objects and #their average size p = flt.canny(image_array) #plt.imshow(p,cmap=plt.cm.gray,interpolation='nearest') #plt.show() labels, count = ndimage.label(p) area = np.sum((labels>0))/count feature.append(area) feature.append(count) #determine the filename for the results file and the image type for the #training set. filename = image_path.split("/")[-1] file_list.append(filename) image = filename.split('_')[0] name_list.append(image) feature_list.append(feature) return name_list, feature_list, file_list
try: path_input = sys.argv[1] path_output = sys.argv[2] except IndexError: raise ValueError("Must specify path (with wildcards) for training data and output") try: files = glob.glob(os.path.expanduser(path_input)) except IOError: print("Could not fetch files from {0}".format(path_input)) sys.exit(0) res = None for i, f in enumerate(files): print(i, f) data = plt.imread(f) if res is None: res = np.zeros((len(files),) + data.shape[:2]) print(len(f)) print(data.shape) res[i] = data[:,:,:3].mean(axis=2) try: np.save(path_output, res) except IOError: print("Could not save to {0}".format(output)) print("SAVED (to {0})".format(path_output))
ImageFile = 'image.jpg' else: print 'I do not know what to do, exiting' exit() def rgb2gray(rgb): ''' convert an image from rgb to grayscale http://stackoverflow.com/a/12201744/323100 ''' return np.dot(rgb[..., :3], [0.299, 0.587, 0.144]) ImageToLoad = os.path.join(ImagePath, ImageDir, Camera, ImageFile) ImageRGB = plt.imread(ImageToLoad) Image = rgb2gray(ImageRGB) plt.imshow(np.fft.fft2(Image)) # plt.imshow(Image) plt.ioff() plt.show() exit() def MTF(edgespreadfunction): ''' Compute the modulation transfer function (MTF).
#!/usr/bin/env python2 import numpy as np from matplotlib import pylab as pl import sys import struct if len(sys.argv) != 3: print "Usage : convert_pic.py img output" exit() file=sys.argv[1] pic = pl.imread(file) pic = pic*1.0 / pic.max() size = [3,3,2] p = [] dd = np.zeros(pic.shape[:-1]).astype(np.int8) for i in range(3): p.append(np.minimum((pic[:,:,i]*(1<<size[i])).astype(np.int32), (1<<size[i])-1)) dd = (dd << size[i]) | p[i] data = struct.pack('>I', pic.shape[0])+struct.pack('>I', pic.shape[1]) for val in dd.flat: data += struct.pack('>B', val) print "dump size:", len(data) open(sys.argv[2], 'w').write(data)
# This file is part of the Astrometry.net suite. # Licensed under a 3-clause BSD style license - see LICENSE try: import pyfits except ImportError: try: from astropy.io import fits as pyfits except ImportError: raise ImportError("Cannot import either pyfits or astropy.io.fits") import math from math import exp from matplotlib.pylab import imread from numpy.oldnumeric.functions import zeros, ravel I = imread("3.png") I = I[:, :, :3] (h, w, planes) = I.shape XY = pyfits.open("16b.fits")[1].data X = XY.field("X") Y = XY.field("Y") psfw = 1.0 stars = zeros((h, w)).astype(float) for (x, y) in zip(X, Y): ix = int(round(x)) iy = int(round(y)) for dy in range(-5, 6): yy = iy + dy if yy < 0 or yy >= h: continue
if options.verbose: print 'Saving images with' print print ffmpegcommand print t0 = time.time() subprocess.call(ffmpegcommand, stdout=DEVNULL, stderr=subprocess.STDOUT, shell=True) t1 = time.time() print "in", str(round(t1 - t0, 3)), "seconds (" +\ str(round(options.images / (t1-t0), 3)) + " images per second)" filename = os.path.join(FileSavePath, "snapshot_%03d" % (int(round(options.images / 2.0))) + ".jpg") image = plt.imread(filename) plt.imshow(image, origin="lower") figuretitle = "Snapshot", str(int(round(options.images / 2.0))), "of",\ str(options.images), "from", FileSavePath, "\nwith an exposure time of",\ str(options.exposuretime / 10), "ms", if options.preview: plt.axhspan(ymin=CMOSheight-previewheight, ymax=CMOSheight, xmin=0, xmax=float(previewwidth)/CMOSwidth, facecolor='r', alpha=0.5) plt.xlim([0, CMOSwidth]) plt.ylim([0, CMOSheight]) figuretitle += "\nred=preview area", plt.title(' '.join(figuretitle)) plt.show() print 'Images saved to',
plt.subplot(gs[1:3, 0]) plt.scatter(VoltageHamamatsu, CurrentHamamatsu, c=colors[0], alpha=0.25, label='Hamamatsu') plt.plot(VoltageERI, CurrentERI, c=colors[1], label='ERI') plt.plot(VoltageMatch, CurrentMatch, c=colors[2], label='Closest Match') plt.xlabel('Voltage [kV]') plt.ylabel('Current [uA]') plt.ylim([0, 75]) plt.legend(loc='best') plt.title('Voltage vs. Current') for c, i in enumerate(CompareImages): print '%s/%s | %s kV/%s uA | Comparing %s with %s' % ( c + 1, len(CompareImages), VoltageERI[c], CurrentERI[c], bold(os.path.basename(i)), bold(os.path.basename(ImageListERI[c]))) ImageERI = plt.imread(ImageListERI[c]) ImageHamamatsu = plt.imread(i) plt.subplot(gs[:2, 1:]) plt.imshow(plt.imread(ImageListERI[c])) plt.axis('off') plt.subplot(gs[2:, 1:]) plt.imshow(plt.imread(i)) plt.axis('off') plt.subplots_adjust(wspace=0.02, hspace=0, left=0.03, right=1, top=1, bottom=0) plt.draw() # Save figure and concatenated results plt.savefig(os.path.join(OutputPath, '%02d' % VoltageERI[c] + 'kV' + str(CurrentERI[c]) + 'uA.png')) ConcatenateImage = numpy.concatenate((ImageERI, ImageHamamatsu), axis=0) plt.imsave(os.path.join(OutputPath, 'Concatenate_%02d' % VoltageERI[c] +
#!/use/bin/env python import numpy as np from pylatticeflow import calculate2dTV, calculate2dTVPath from matplotlib.pylab import imread, figure, show from matplotlib import collections from itertools import product plot_type = "levels2" image_file = "benchmarks/images/truffles.png" #image_file = "benchmarks/images/truffles-small.png" # image_file = "benchmarks/images/sanity.png" #image_file = "benchmarks/images/branches-small.png" Xo = imread(image_file) if not Xo.size: raise IOError("Error loading image %s." % image_file) X = (Xo.mean(axis=2) / Xo.max())[::2, ::2] X -= X.mean() X /= X.std() # X = np.linspace(0,1.25,6).reshape( (3,2) ) # Xtv0 = calculate2dTV(X, 0) # assert abs(X - Xtv0).mean() <= 1e-4, abs(X - Xtv0).mean()
def test_it(): import matplotlib.pylab as plt import numpy from matplotlib.pylab import imread import time im = \ imread('/Users/davidcox/Repositories/coxlab/eyetracker/ImageProcessing/RatEye_snap12_zoom.jpg' ) im = im.astype(numpy.float64) noplot = 1 f = FastRadialFeatureFinder() f.return_sobel = True trials = 100 if 0: tic = time.time() for i in range(0, trials): test = f.analyze_image(im, filter='fft') print 'FFT: ', (time.time() - tic) / trials plt.figure() plt.imshow(test['transform']) plt.title('FFT') if 1: f.reuse_storage = 0 f.use_sse3 = 0 f.filter = 'sepfir' f.analyze_image(im, filter='sepfir') test = f.get_result() tic = time.time() for i in range(0, trials): f.analyze_image(im, filter='sepfir') test = f.get_result() seconds_per_frame = (time.time() - tic) / trials print 'Sep FIR: ', seconds_per_frame # print '\t ', 1. / seconds_per_frame, ' FPS' if not noplot: plt.figure() plt.imshow(test['transform']) plt.figure() # pylab.imshow(test['im_array'], cmap=pylab.cm.gray) plt.imshow(test['sobel'], cmap=pylab.cm.gray) plt.hold('on') cr = test['cr_position'] pupil = test['pupil_position'] plt.plot([cr[1]], [cr[0]], 'r+') plt.plot([pupil[1]], [pupil[0]], 'b+') plt.title('Sep FIR') if 0: tic = time.time() for i in range(0, trials): test = f.analyze_image(im, filter='spline') print 'SPLINE: ', (time.time() - tic) / trials plt.figure() plt.imshow(test['transform']) plt.title('SPLINE') if 0: tic = time.time() for i in range(0, trials): test = f.analyze_image(im) print 'Convolve2d: ', (time.time() - tic) / trials plt.figure() plt.imshow(test['transform']) plt.title('Convolve2d') if 0: f.reuse_storage = 1 tic = time.time() def sepfir_multithread_test(i, f, im): test = f.analyze_image(im, filter='sepfir') foreach(lambda t: sepfir_multithread_test(t, f, im), range(0, trials), 3) print 'Sep FIR (multithreaded): ', (time.time() - tic) / trials
def FillingTheGap(save=False): ## ComPair fig = plot.figure() yrange = [1e-6,4e-3]#[1e-13, 1e2] xrange = [1e-3,1e7] plot.fill_between([0.2,10e3],[yrange[1],yrange[1]],[yrange[0],yrange[0]],facecolor='yellow',interpolate=True,color='yellow',alpha=0.5) plot.annotate('AMEGO',xy=(4,1.5e-3),xycoords='data',fontsize=26,color='black') ## AGN a=ascii.read("data/marco_AGN_data_points_fig_6.txt",names=['logfreq','logflux']) logfreq=a['logfreq'] logflux=a['logflux'] h=6.6261e-27 #erg s erg2mev=624151. agn_energy=10**logfreq*h*erg2mev #Hz * erg s arbfact=5 agn_flux=10**logflux*erg2mev*arbfact #erg cm-2 s-1 i = np.where(agn_energy < 0.1) plot.plot(agn_energy[i],agn_flux[i],color='navy',lw=2) i = np.where((agn_energy > 0.1) & (agn_energy < 200)) plot.plot(agn_energy[i],agn_flux[i],'r--',color='navy',lw=2) i=np.where(agn_energy > 200) plot.plot(agn_energy[i],agn_flux[i],color='navy',lw=2) b=ascii.read("data/0641_0320nustar_torus.dat",names=['x','y','z','tot','f','fbump','ftot','syn','ssc','ext1c']) logfreq=b['x'] lognufnu=b['ftot'] agn_energy2=10**logfreq*h*erg2mev agn_flux2=10**lognufnu*erg2mev*arbfact i = np.where(agn_energy2 < 0.1) plot.plot(agn_energy2[i],agn_flux2[i],color='cornflowerblue',lw=2) i = np.where((agn_energy2 > 0.1) & (agn_energy2 < 200)) plot.plot(agn_energy2[i],agn_flux2[i],'r--',color='cornflowerblue',lw=2) i=np.where(agn_energy2 > 200) plot.plot(agn_energy2[i],agn_flux2[i],color='cornflowerblue',lw=2) xrt=ascii.read("data/0641_0320xrt.dat",names=['logfreq','logflux']) xrt_energy=(10**xrt['logfreq'])*h*erg2mev xrt_flux=(10**xrt['logflux'])*erg2mev*arbfact plot.scatter(xrt_energy,xrt_flux,color='blue') nustar=ascii.read("data/0641_0320nustar_ajello_fab.dat",names=['logfreq','logflux','logflux_yerr0','logflux_yerr1']) ns_energy=(10**nustar['logfreq'])*h*erg2mev ns_flux=(10**nustar['logflux'])*erg2mev*arbfact plot.scatter(ns_energy,ns_flux,color='blue') lat=ascii.read("data/LAT_spec_NuSTARobs2.txt",names=['ener','ed_ener','eu_ener','flux','ed_flux','eu_flux','ulim_flux','TS','Npred']) plot.scatter(lat['ener'],lat['flux']*arbfact) plot.errorbar(lat['ener'][0:3],lat['flux'][0:3]*arbfact,xerr=[lat['ed_ener'][0:3],lat['eu_ener'][0:3]],yerr=[lat['ed_flux'][0:3]*arbfact,lat['eu_flux'][0:3]*arbfact],capsize=0,fmt="none") ## Pulsar example pulsar_eng=np.array([0.012943256,0.018285165,0.031053474,0.05153211,0.08552302,0.21973862,137.03448,237.55414]) pulsar_flux=np.array([1.7420283E-5,2.2255874E-5,3.0082629E-5,3.842357E-5,5.0966246E-5,7.149577E-5,1.4489453E-5,6.674534E-6]) pulsar_eng_ul=np.array([421.64273,748.32324]) pulsar_flux_ul=np.array([4.0049385E-6,2.314023E-6]) xs = np.linspace(np.min(np.log10(1e-3)), np.max(np.log10(1e3)), 300) pulsar_Energy = 10**xs e0=[0.100518,0.100518*0.4,0.100518] # norm energy k=[1.574e-2,1.574e-2*2,1.574e-2*5] # normalization gamma=[-1.233,-1.18,-1.2] # ec=[0.078,0.8,5e-4] #cutoff energy beta=[0.286,0.4,0.18] # cutoff slope arbfact=1 color=['darkgreen','sage'] for j in range(0,2): flux=k[j]*(pulsar_Energy/e0[j])**gamma[j]*np.exp(-(pulsar_Energy/ec[j])**beta[j]) pulsar_Flux=flux*pulsar_Energy**2 i = np.where(pulsar_Energy < 0.2) plot.plot(pulsar_Energy[i],pulsar_Flux[i]*arbfact,color=color[j],lw=2) i = np.where((pulsar_Energy > 0.2) & (pulsar_Energy < 100)) plot.plot(pulsar_Energy[i],pulsar_Flux[i]*arbfact,'r--',color=color[j],lw=2) i=np.where(pulsar_Energy > 100) plot.plot(pulsar_Energy[i],pulsar_Flux[i]*arbfact,color=color[j],lw=2) plot.scatter(pulsar_eng,pulsar_flux*arbfact,color='green') errfrac=np.concatenate((np.repeat(0.1,6),(0.4,0.6)),axis=0) plot.errorbar(pulsar_eng,pulsar_flux*arbfact,yerr=errfrac*pulsar_flux*arbfact,color='green',ecolor='green',capsize=0,fmt="none") plot.errorbar(pulsar_eng_ul,pulsar_flux_ul*arbfact,yerr=0.5*pulsar_flux_ul*arbfact,color='green',ecolor='green',capsize=0,uplims=True,fmt="none") plot.scatter(pulsar_eng_ul,pulsar_flux_ul*arbfact,color='green') ## Nova arbfact=0.5 #osse=ascii.read("data/NVel1999.OSSE.dat",names=['energy','en_low','en_high','flux','flux_err']) #plot.scatter(osse['energy'],osse['flux']*erg2mev*arbfact,color='red') #plot.errorbar(osse['energy'],osse['flux']*erg2mev*arbfact,xerr=[osse['en_low'],osse['en_high']],yerr=osse['flux_err']*erg2mev*arbfact,ecolor='red',capsize=0,fmt='none') lat=ascii.read("data/NMon2012.LAT.dat",names=['energy','en_low','en_high','flux','flux_err','tmp']) plot.scatter(lat['energy'],lat['flux']*erg2mev*arbfact,color='red') plot.errorbar(lat['energy'],lat['flux']*erg2mev*arbfact,xerr=[lat['en_low'],lat['en_high']],yerr=lat['flux_err']*erg2mev*arbfact,ecolor='red',capsize=0,fmt='none') latul=ascii.read("data/NMon2012.LAT.limits.dat",names=['energy','en_low','en_high','flux','tmp1','tmp2','tmp3','tmp4']) plot.errorbar(latul['energy'],latul['flux']*erg2mev*arbfact,xerr=[latul['en_low'],latul['en_high']],yerr=0.5*latul['flux']*erg2mev*arbfact,uplims=True,ecolor='red',capsize=0,fmt='none') plot.scatter(latul['energy'],latul['flux']*erg2mev*arbfact,color='red') #models=ascii.read("data/data-NovaMon2012.txt",names=['energy','leptonic','hadronic'],data_start=1) #mo=['leptonic','hadronic'] colors=['orangered','coral','darkred'] leptonic=ascii.read("data/sp-NMon12-IC-best-fit-1MeV-30GeV.txt",names=['energy','flux'],data_start=1) hadronic=ascii.read("data/sp-NMon12-pi0-and-secondaries.txt",names=['energy','flux1','flux2'],data_start=1) for j in range(0,2): if (j == 0): energy=leptonic['energy'] flux=leptonic['flux'] if (j == 1): energy=hadronic['energy'] flux=hadronic['flux2'] if (j == 2): flux=hadronic['flux1'] i=np.where(energy < 0.2) plot.plot(energy[i],flux[i]*erg2mev*arbfact,color=colors[j],lw=2) i=np.where((energy > 0.2) & (energy <100 )) plot.plot(energy[i],flux[i]*erg2mev*arbfact,'r--',color=colors[j],lw=2) i=np.where(energy > 100) plot.plot(energy[i],flux[i]*erg2mev*arbfact,color=colors[j],lw=2) # PWNe # From Torres et al. JHEAP, 2014, 1, 31 # G54.1+0.3 # arbfact=1#e-3 # pwne_model_eng=np.array([860.1604,1866.5002,3879.583,7087.079,10898.913,17498.09,28093.0,34838.23,41383.043,299664.66,6644004.5,3.5596056E7,1.29464152E8,4.91573856E8,3.71615181E9,2.36500337E10,8.2392531E10,2.52272067E11,5.47416343E11,8.7887118E11])*1e-6 # pwne_model_flux=np.array([1.2608298E-11,9.389613E-12,5.4490882E-12,2.8233574E-12,1.1928516E-12,4.0173412E-13,1.7362255E-13,1.3226478E-13,1.4482099E-13,3.1305714E-13,7.409742E-13,8.684221E-13,8.2992185E-13,6.3223027E-13,2.9917822E-13,8.0318205E-14,1.925147E-14,4.119833E-15,8.816484E-16,1.0E-16])*erg2mev*arbfact # xs = np.linspace(np.min(np.log10(1e-3)), np.max(np.log10(5e3)), 300) # pwne_Energy=10**xs # tck=interpolate.splrep(np.log10(pwne_model_eng),np.log10(pwne_model_flux),s=0) # pwne_Flux=10**interpolate.splev(np.log10(pwne_Energy),tck,der=0) # pwne_data_eng=np.array([1.7125564E7,5.4741636E7,1.74980896E8,2.46901296E8,3.9639744E8,6.3641197E8,1.11359936E9,1.64041331E9,2.52272051E9,4.0502016E9])*1e-6 # pwne_data_upper_flux=np.array([4.2462813E-12,4.7560116E-12,1.5817023E-11,3.7911818E-12,1.2202063E-12,2.2001422E-12,1.8772538E-12,2.6377E-12,1.1144125E-12,2.1508195E-12])*erg2mev*arbfact # pwne_data_flux=np.array([0,0,0,1.4628772E-12,3.2757992E-13,8.489537E-13,7.579663E-13,1.2202063E-12,2.3313897E-13,6.9224937E-13])*erg2mev*arbfact # pwne_data_lower_flux=np.array([8.883369E-13,1.1144125E-12,3.3089764E-12,3.5867788E-13,3.242955E-14,3.5867788E-13,2.4395433E-13,5.039727E-13,1.7188176E-14,1.2356735E-13])*erg2mev*arbfact # i = np.where(pwne_Energy < 0.5) # plot.plot(pwne_Energy[i],pwne_Flux[i],color='red',lw=2) # i = np.where((pwne_Energy > 0.5) & (pwne_Energy < 200)) # plot.plot(pwne_Energy[i],pwne_Flux[i],'r--',color='red',lw=2) # i=np.where(pwne_Energy > 200) # plot.plot(pwne_Energy[i],pwne_Flux[i],color='red',lw=2) # plot.errorbar(pwne_data_eng[3:],pwne_data_flux[3:],yerr=[pwne_data_flux[3:]-pwne_data_lower_flux[3:],pwne_data_upper_flux[3:]-pwne_data_flux[3:]],color='tomato',fmt='o',ecolor='tomato',capsize=0,lw=2) # plot.errorbar(pwne_data_eng[0:3],pwne_data_upper_flux[0:3],yerr=pwne_data_upper_flux[0:3]-pwne_data_lower_flux[0:3],color='tomato',fmt='o',ecolor='tomato',uplims=True,lw=2) # plot stuff plot.xscale('log') plot.yscale('log') plot.ylim(yrange) plot.xlim(xrange) plot.xlabel(r'Energy (MeV)') plot.ylabel(r'Energy$^2 \times $ Flux (Energy) (arbitrarily scaled)') im1=plot.imread('data/AGN_UnifiedModel.jpg') newax1=fig.add_axes([0.73,0.65,0.15,0.15],anchor='NE') newax1.imshow(im1) for axis in ['top','bottom','right','left']: newax1.spines[axis].set_linewidth(4) newax1.spines[axis].set_color('blue') newax1.set_xticks([]) newax1.set_yticks([]) # newax1.axis('off') plot.title('Jets',color='blue',fontsize=12) im2=plot.imread('data/pulsar.jpg') newax2=fig.add_axes([0.73,0.4,0.15,0.16],anchor='NE') newax2.imshow(im2) for axis in ['top','bottom','right','left']: newax2.spines[axis].set_linewidth(4) newax2.spines[axis].set_color('green') newax2.set_xticks([]) newax2.set_yticks([]) # newax2.axis('off') plot.title('Compact Objects',color='green',fontsize=12) im3=plot.imread('data/Classical_Nova_Final.jpg') newax3=fig.add_axes([0.73,0.18,0.15,0.15],anchor='NE') newax3.imshow(im3) for axis in ['top','bottom','right','left']: newax3.spines[axis].set_linewidth(4) newax3.spines[axis].set_color('red') newax3.set_xticks([]) newax3.set_yticks([]) # newax3.axis('off') plot.title('Shocks',color='red',fontsize=12) if save: #plot.savefig('SED_science_themes.eps', bbox_inches='tight') plot.savefig('SED_science_themes.pdf', bbox_inches='tight') plot.savefig('SED_science_themes.png', bbox_inches='tight') plot.show() plot.close() ## to do ### add colored box around each image ### add labels for jets, compact objects, shocks + maybe source type return
print 'and showing it in a matplotlib-figure' print print 'rinse, lather, repeat' Counter = 0 StartTime = time.time() try: while True: FileName = 'Snapshot_' + str('%.04d' % Counter) + '.jpg' DownScale = 10 urllib.urlretrieve(CamIP + ':8081/img', os.path.join(os.getcwd(), SubDirName, 'Snapshots', FileName)) if options.Verbose: print 'I have written image', Counter, 'as',\ os.path.join(os.getcwd(), SubDirName, FileName) plt.imshow(plt.imread(os.path.join(os.getcwd(), SubDirName, 'Snapshots', FileName) )[::DownScale, ::DownScale, :], origin='lower', interpolation='nearest') TimeUsed = time.time() - StartTime ImageTitle = str(FileName) + ' written in ' +\ str(int(np.round(TimeUsed))) + ' s = (' +\ str(np.round(Counter / TimeUsed, decimals=3)) +\ ' img/s) \nshown ' + str(DownScale) + 'x downscaled' plt.title(ImageTitle) Counter += 1 plt.draw() except KeyboardInterrupt: print '\nGoodbye' # switch back to normal matplotlib behaviour plt.ioff() elif options.Trigger:
def getData(self, Directory = None, GroupName = None): """Find data in a database or import it if it does not exist. :param Directory: list of directories of images to analyze. :type Directory: list :param GroupName: name of groups in directory list. If None a name \ is approximated based on directory paths :type GroupName: str :returns: Amplitude spectrum :return type: numpy.array This function will find all jpg files in the list of directories check to see if they are in the HDF5 ImageDatabase, import them if they are not, and return the amplitude spectrum for the group. .. todo:: * ``high prior`` Compute Information for images as well. * ``low prior`` make a gui - use the database gui. Introduce images. """ if not Directory: if sys.platform == 'darwin': Directory = ['/Users/brianschmidt/Documents/cd01A/'] index = [-6, -1] if sys.platform == 'win32': Directory = ['C:/Data/UPenn_Images/Images/cd01A', 'C:/Data/UPenn_Images/Images/cd02A', 'C:/Data/UPenn_Images/Images/cd06A', 'C:/Data/UPenn_Images/Images/cd32A', 'C:/Data/UPenn_Images/Images/cd38A', 'C:/Data/UPenn_Images/Images/cd41A', 'C:/Data/UPenn_Images/Images/cd58A'] index = [-5, len(Directory[0])] self.ampSpecs = [] self.rawAmp= [] for group in Directory: GroupName = group[index[0]:index[1]] files = f.getAllFiles(group, suffix='.JPG', subdirectories=1) if self.Dbase.Exists(GroupName) == False: self.Dbase.CreateGroup(GroupName) for path in files: img = None imgBW = None amplitude = None name = os.path.basename(path[:-4]) # remove .jpg if self.Dbase.Exists(name, GroupName) == False: self.Dbase.CreateGroup(name, GroupName) # subnode == Image if self.Dbase.Exists('Image', GroupName + '.' + name) == False: self.Dbase.CreateGroup('Image', GroupName + '/' + name) if self.Dbase.Exists('raw_image', GroupName + '.' + name + '.Image') == False: img = imread(path) self.Dbase.AddData2Database('raw_image', img, GroupName + '.' + name + '.Image') if self.Dbase.Exists('grayscale', GroupName + '.' + name + '.Image') == False: if img == None: img = self.Dbase.QueryDatabase(GroupName, name + '.' + 'Image', 'raw_image') imgBW = sig.rgb2gray(img) self.Dbase.AddData2Database('grayscale', img, GroupName + '.' + name + '.Image') # metadata stuff: if self.Dbase.Exists('path', GroupName + '.' + name) == False: self.Dbase.AddData2Database('path', np.array([path], dtype=str), GroupName + '.' + name) if self.Dbase.Exists('goodFile', GroupName + '.' + name) == False: goodFile = self.getGoodFiles(path) self.Dbase.AddData2Database('goodFile', np.array([goodFile], dtype=bool), GroupName + '.' + name) else: goodFile = self.Dbase.QueryDatabase(GroupName, name, 'goodFile') # subnode == Amplitude spectrum if self.Dbase.Exists('amplitude', GroupName + '.' + name) == False: self.Dbase.CreateGroup('amplitude', GroupName + '/' + name) # raw amplitude spectrum first if self.Dbase.Exists('raw_amplitude', GroupName + '.' + name + '.' + 'amplitude') == False: if imgBW == None: imgBW = self.Dbase.QueryDatabase(GroupName, name + '.' 'Image', 'grayscale') amplitude = sig.welch2d(imgBW[500:2000, 500:2000]) self.Dbase.AddData2Database('raw_amplitude', amplitude, GroupName + '.' + name + '.' + 'amplitude') if goodFile != False or goodFile != 'F': self.rawAmp.append(amplitude) else: pass else: if goodFile != False or goodFile != 'F': self.rawAmp.append(self.Dbase.QueryDatabase(GroupName, name + '.' + 'amplitude', 'raw_amplitude')) # then amplitude density if self.Dbase.Exists('amplitude_density', GroupName + '.' + name + '.' + 'amplitude') == False: if amplitude == None: amplitude = self.Dbase.QueryDatabase(GroupName, name + '.' + 'amplitude', 'raw_amplitude') amplitude = sig.Density(amplitude) self.Dbase.AddData2Database('amplitude_density', amplitude, GroupName + '.' + name + '.' + 'amplitude') if goodFile != False or goodFile != 'F': self.ampSpecs.append(amplitude) # if already exists, query database to get amplitude spectrums: else: if goodFile: self.ampSpecs.append( self.Dbase.QueryDatabase(GroupName, name + '.' + 'amplitude', 'amplitude_density')) self.Dbase.file.flush() self.Dbase.CloseDatabase() self.amp_mean = np.zeros((self.ampSpecs[0].shape)) total_images = len(self.ampSpecs) print 'number of images: ', total_images for amp in self.ampSpecs: self.amp_mean += amp / total_images
def test_it(): import matplotlib.pylab as plt import numpy from matplotlib.pylab import imread import time im = imread("/Users/davidcox/Repositories/coxlab/eyetracker/ImageProcessing/RatEye_snap12_zoom.jpg") im = im.astype(numpy.float64) noplot = 1 f = FastRadialFeatureFinder() f.return_sobel = True trials = 100 if 0: tic = time.time() for i in range(0, trials): test = f.analyze_image(im, filter="fft") print "FFT: ", (time.time() - tic) / trials plt.figure() plt.imshow(test["transform"]) plt.title("FFT") if 1: f.reuse_storage = 0 f.use_sse3 = 0 f.filter = "sepfir" f.analyze_image(im, filter="sepfir") test = f.get_result() tic = time.time() for i in range(0, trials): f.analyze_image(im, filter="sepfir") test = f.get_result() seconds_per_frame = (time.time() - tic) / trials print "Sep FIR: ", seconds_per_frame # print '\t ', 1. / seconds_per_frame, ' FPS' if not noplot: plt.figure() plt.imshow(test["transform"]) plt.figure() # pylab.imshow(test['im_array'], cmap=pylab.cm.gray) plt.imshow(test["sobel"], cmap=pylab.cm.gray) plt.hold("on") cr = test["cr_position"] pupil = test["pupil_position"] plt.plot([cr[1]], [cr[0]], "r+") plt.plot([pupil[1]], [pupil[0]], "b+") plt.title("Sep FIR") if 0: tic = time.time() for i in range(0, trials): test = f.analyze_image(im, filter="spline") print "SPLINE: ", (time.time() - tic) / trials plt.figure() plt.imshow(test["transform"]) plt.title("SPLINE") if 0: tic = time.time() for i in range(0, trials): test = f.analyze_image(im) print "Convolve2d: ", (time.time() - tic) / trials plt.figure() plt.imshow(test["transform"]) plt.title("Convolve2d") if 0: f.reuse_storage = 1 tic = time.time() def sepfir_multithread_test(i, f, im): test = f.analyze_image(im, filter="sepfir") foreach(lambda t: sepfir_multithread_test(t, f, im), range(0, trials), 3) print "Sep FIR (multithreaded): ", (time.time() - tic) / trials
Image(filename='camera_down.jpg') Image(filename='Num_Ex_3/TeX_7.jpg') get_ipython().magic(u'pwd ') Image(filename='Num_Ex_3\\TeX_7.jpg') Image(filename='Num_Ex_3\\camera_blurred_1.jpg') Image(filename='Num_Ex_3\\camera_blurred_1.png') Image(filename='Num_Ex_3/camera_blurred_1.png') Image(filename='Num_Ex_3/camera_blurred_big.jpg') Image(filename='Num_Ex_3/camera_blurred.jpg') Image(filename='Num_Ex_3/camera_blurred_big_1.jpg') runfile('D:/dev/DSP/DSPNumex/NumEx3/grayscale.py', wdir='D:/dev/DSP/DSPNumex/NumEx3') from IPython.display import Image Image(filename='Num_Ex_3/camera_blurred_big_1.jpg') get_ipython().magic(u'pylab inline') import matplotlib.pylab as plt I = np.array(plt.imread('Num_Ex_3/camera_blurred.jpg'), dtype=float64) I[:,0] len(I) len(I[0]) I[0] import matplotlib.pylab as plt plt.imshow(I, cmap=plt.cm.gray, interpolation='none') #The cmap=plt.cm.gray renders the image in gray plt.show() import matplotlib.pylab as plt I_approx = np.array(plt.imread('Num_Ex_3/camera_blurred.jpg'), dtype=float64) I_approx[:,0] I_approx[0] Image(filename='Num_Ex_3/camera_blurred.jpg') I_approx[:,I_approx.shape[1]/2:] = 0 plt.imshow(I_approx, cmap=plt.cm.gray, interpolation='none') plt.title('Approximation')
def loadim(impath): '''load image and rescale on 0-1''' im = plt.imread(impath) im = skimage.img_as_float(im) im = (im - im.min()) / (im.max() - im.min()) return im
#Size = fig_bmp.shape #print 'Size: ', Size #GCF = pylab.gcf() #DPI = GCF.get_dpi() #print "DPI: ", DPI #b_box_1 = (top, left, bottom,right) #b_box_1 = (10,10,200,200) #a = a.crop(b_box_1); ax3 = pylab.subplot(gs[1]) pylab.title(string_time,fontsize=40) #b = pylab.imread(tv03_file) b = pylab.imread('tv03_tmp.png') fig_tv03=pylab.mean(b,2) print 'done' #fig_bmp = Image.open(datafile) #dpi = pylab.rcParams['figure.dpi'] #figsize = fig_bmp.size[0]/dpi, fig_bmp.size[1]/dpi #figure(figsize=figsize) #ax2.axis('scaled') #ax2.get_xaxis().set_ticks([]);