我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用imageio.imread()。
def load_data_into_memory(DIR, ANNO, ATTRIBUTE, normalize=True, rollaxis=True): if DIR[:-1] != '/': DIR += '/' df = parse_csv(ANNO) files = filter(lambda x: x in df.index.values, os.listdir(DIR)) X, y = [], [] for image_path in progress.bar(files): img = imageio.imread(DIR + image_path) if normalize: img = img.astype('float32') / 255. if rollaxis: img.shape = (1,150,130) else: img.shape = (150,130,1) X.append(img) mu = df[ATTRIBUTE][image_path] y.append(mu) y = np.array(y) y = y - min(y) y = np.float32(y / max(y)) x, y = np.array(X), np.array(y) print 'Loaded {} images into memory'.format(len(y)) return x, y
def create_composite_image_coin_id(coin_id, crop_dir, data_dir): images = [] images_gif = [] for id in range(0,56): image_id = coin_id * 100 + id crop = ci.get_rotated_crop(crop_dir, image_id, 56, 0) images.append(crop) filename = ci.get_filename_from(image_id,crop_dir) images_gif.append(imageio.imread(filename)) composite_image = ci.get_composite_image(images, 8, 8) cv2.imwrite(data_dir + str(coin_id) + '.png', composite_image) imageio.mimsave(data_dir + str(coin_id) + '.gif', images_gif) return
def draw1DMovie(solution, t_filming_step, x_start, x_end, legend, t_grid_step): #??????? ????? ?? ?????????? img\ ????? ????????? ????????. files = glob.glob('img' + os.sep + '*') for f in files: os.remove(f) #???????? ????????? ?????? ?? ??????? ? ?????. for i in range(0, solution.shape[0], t_filming_step): draw1DSlice(solution[i], i * t_grid_step, x_start, x_end, legend, np.max(solution)) #?????? ????? ?? ??????????? ????? img\, ????????? ?? ???? ??. images = [] filenames = sorted(fn for fn in os.listdir(path='img' + os.sep) if fn.endswith('.png')) for filename in filenames: images.append(imageio.imread('img' + os.sep + filename)) imageio.mimsave('img' + os.sep + 'movie.gif', images, duration = 0.1)
def process_single_image(filename, image_format, scale_metadata_path, threshold_radius, smooth_radius, brightness_offset, crop_radius, smooth_method): image = imageio.imread(filename, format=image_format) scale = _get_scale(image, scale_metadata_path) if crop_radius > 0: c = crop_radius image = image[c:-c, c:-c] pixel_threshold_radius = int(np.ceil(threshold_radius / scale)) pixel_smoothing_radius = smooth_radius * pixel_threshold_radius thresholded = pre.threshold(image, sigma=pixel_smoothing_radius, radius=pixel_threshold_radius, offset=brightness_offset, smooth_method=smooth_method) quality = shape_index(image, sigma=pixel_smoothing_radius, mode='reflect') skeleton = morphology.skeletonize(thresholded) * quality framedata = csr.summarise(skeleton, spacing=scale) framedata['squiggle'] = np.log2(framedata['branch-distance'] / framedata['euclidean-distance']) framedata['scale'] = scale framedata.rename(columns={'mean pixel value': 'mean shape index'}, inplace=True) framedata['filename'] = filename return image, thresholded, skeleton, framedata
def modify(self, function, *args, **kwargs): """ Modify the image object using the given Image function. This function supplies sequence support. """ if not gif_support or not self.gif: self.object = function(self.object, *args, **kwargs) else: frames = [] duration = self.object.info.get("duration") / 1000 for frame in ImageSequence.Iterator(self.object): frame_bytes = utils.convert_image_object(function(frame, *args, **kwargs)) frames.append(imageio.imread(frame_bytes, format="PNG")) # Save the image as bytes and recreate the image object image_bytes = imageio.mimwrite(imageio.RETURN_BYTES, frames, format=self.format, duration=duration) self.object = Image.open(BytesIO(image_bytes)) self.gif_bytes = image_bytes
def add_image(self, image): """ This function ... :param image: :return: """ # Create an animation to show the result of the source extraction step if self.max_frame_value is None: self.max_frame_value = np.nanmax(image) # Make a plot of the image buf = io.BytesIO() plotting.plot_box(image, path=buf, format="png", vmin=0.0, vmax=0.5*self.max_frame_value) buf.seek(0) im = imageio.imread(buf) buf.close() self.add_frame(im) # -----------------------------------------------------------------
def cmd_info(message, parameters, recursion=0): await client.send_typing(message.channel) async for msg in client.logs_from(message.channel, limit=25): try: if msg.attachments: img = Image.open(BytesIO(requests.get(msg.attachments[0]['url']).content)).convert('RGB') neg = ImageOps.invert(img) neg.save("tmp/negative.png","PNG") img.save("tmp/positive.png","PNG") frames = [imageio.imread("tmp/negative.png"), imageio.imread("tmp/positive.png")] imageio.mimsave("tmp/epilepsy.gif", frames, duration=0.07) with open("tmp/epilepsy.gif", "rb") as outputGif: await client.send_file(message.channel, outputGif, filename="epilepsy.gif") os.system("rm tmp/epilepsy.gif tmp/negative.png tmp/positive.png") return except Exception as e: e = discord.Embed(colour=0xB5434E) e.description = "Error ocurred, 2 lazy to check what was it, try again later." await client.send_message(message.channel, embed=e) return
def make_gif(self, frame_count_limit=IMAGE_LIMIT, gif_name="mygif.gif", frame_duration=0.4): """Make a GIF visualization of view graph.""" self.make_thumbnails(frame_count_limit=frame_count_limit) file_names = sorted([file_name for file_name in os.listdir(self.thumbnail_path) if file_name.endswith('thumbnail.png')]) images = [] for file_name in file_names: images.append(Image.open(self.thumbnail_path + file_name)) destination_filename = self.graph_path + gif_name iterator = 0 with io.get_writer(destination_filename, mode='I', duration=frame_duration) as writer: for file_name in file_names: image = io.imread(self.thumbnail_path + file_name) writer.append_data(image) iterator += 1 writer.close()
def read_split_image(img): mat = misc.imread(img).astype(np.float) side = int(mat.shape[1] / 2) assert side * 2 == mat.shape[1] img_A = mat[:, :side] # target img_B = mat[:, side:] # source return img_A, img_B
def compile_frames_to_gif(frame_dir, gif_file): frames = sorted(glob.glob(os.path.join(frame_dir, "*.png"))) print(frames) images = [misc.imresize(imageio.imread(f), interp='nearest', size=0.33) for f in frames] imageio.mimsave(gif_file, images, duration=0.1) return gif_file
def save_gray(src_dir, dst_dir, size): for full_filename in glob.iglob(src_dir + '*.png'): image = cv2.imread(full_filename) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) small = cv2.resize(gray, (size, size), interpolation=cv2.INTER_AREA) new_filename = full_filename.replace(src_dir, dst_dir) cv2.imwrite(new_filename, small)
def gif(run): images = [] filenames = [x for x in listdir(location) if filetype in x] filenames.sort() for filename in filenames: fqfn = ''.join([location,filename]) images.append(imread(fqfn)) remove(fqfn) fqgn = ''.join([location,gifname,str(run),'.gif']) mimsave(fqgn, images)
def image(): rundir = os.path.abspath(os.path.dirname(__file__)) datadir = os.path.join(rundir, 'data') image = imageio.imread(os.path.join(datadir, 'retic.tif'), format='fei') return image
def make_gif(parent_folder,frame_duration=0.3): items = os.listdir(parent_folder) png_filenames = [] for elem in items: if elem.find(".png")!=-1 and elem.find("heatmap")!=-1: png_filenames.append(elem) sorted_png = [] while True: lowest = 10000000 lowest_idx = -1 for p in png_filenames: old_save_format=False if old_save_format: iter_val = int(p.split("-")[2].split(":")[1]) epoch_val = int(p.split("-")[3].split(":")[1].split(".")[0]) val = float(iter_val)+0.1*epoch_val else: iter_val = int(p.split("-")[3].split(":")[1].split(".")[0]) epoch_val = int(p.split("-")[2].split(":")[1]) val = float(epoch_val)+0.1*iter_val if lowest_idx==-1 or val<lowest: lowest = val lowest_idx = png_filenames.index(p) sorted_png.append(png_filenames[lowest_idx]) del png_filenames[lowest_idx] if len(png_filenames)==0: break png_filenames = sorted_png with imageio.get_writer(parent_folder+"/prediction-heatmap.gif", mode='I',duration=frame_duration) as writer: for filename in png_filenames: image = imageio.imread(parent_folder+"/"+filename) writer.append_data(image)
def add_point(self, x, y, z): """ This function ... :return: """ # Add a point to the plotter self._plotter.add_point(x, y, z) buf = io.BytesIO() self._plotter.set_x_limits(self.x_limits[0], self.x_limits[1]) self._plotter.set_y_limits(self.y_limits[0], self.y_limits[1]) self._plotter.set_z_limits(self.z_limits[0], self.z_limits[1]) if self.x_label is not None: self._plotter.set_x_label(self.x_label) if self.y_label is not None: self._plotter.set_y_label(self.y_label) if self.z_label is not None: self._plotter.set_z_label(self.z_label) self._plotter.format = "png" self._plotter.density = self.density # Run the scatter plotter self._plotter.run(buf) buf.seek(0) im = imageio.imread(buf) buf.close() self.add_frame(im) # Clear the scatter plotter self._plotter.clear_figure() # -----------------------------------------------------------------
def add_value(self, value): """ This function ... :param value: :return: """ # Add the value to the list self.values.append(value) # Create the new (normalized) distribution new_distribution = Distribution.from_values(self.values) new_distribution.normalize(1.0, method="max") buf = io.BytesIO() # Add the reference distributions for label in self.reference_distributions: self._plotter.add_distribution(self.reference_distributions[label], label) # Add the new distribution self._plotter.add_distribution(new_distribution, self.label) self._plotter.set_variable_name(self.variable_name) self._plotter.run(buf, format="png", min_value=self.min_value, max_value=self.max_value, max_count=1., logscale=True) buf.seek(0) im = imageio.imread(buf) buf.close() self.add_frame(im) # Clear the plotter self._plotter.clear() # -----------------------------------------------------------------
def animate(self): """ This function ... :return: """ # Inform the user log.info("Creating an animation of the SED fitting procedure ...") # Create an Animation instance self.animation = Animation() # Loop over the entries of the chi squared table (sorted by decreasing chi squared) for i in range(len(self.chi_squared)): # Get the name of the simulation simulation_name = self.chi_squared["Simulation name"][i] # Determine the path to the corresponding SED plot file path = fs.join(self.fit_plot_path, simulation_name, "sed.png") # Load the image (as a NumPy array) image = imageio.imread(path) # Add the image to the animation self.animation.add_frame(image) # -----------------------------------------------------------------
def triggered(cmd, message, args): if message.mentions: target = message.mentions[0] else: target = message.author if not cmd.cooldown.on_cooldown(cmd, message): cmd.cooldown.set_cooldown(cmd, message, 180) avatar_url = user_avatar(target) + '?size=512' wait_trig_response = discord.Embed(color=0xff6600, title='?? Triggering...') resp_msg = await message.channel.send(embed=wait_trig_response) async with aiohttp.ClientSession() as session: async with session.get(avatar_url) as data: avatar_data = await data.read() avatar = Image.open(BytesIO(avatar_data)) avatar = avatar.resize((300, 300), Image.ANTIALIAS) image_list = [] for x in range(0, 30): base = Image.new('RGBA', (256, 320), (0, 0, 0, 0)) with Image.open(cmd.resource('trig_bot.png')) as trig_sign: move_max = 22 move_x = random.randint(-move_max, move_max) move_y = random.randint(-move_max, move_max) base.paste(avatar, (-22 + move_x, -22 + move_y)) base.paste(trig_sign, (0, 256)) temp_loc = f'temp_gif_cache_{random.randint(99, 999999)}.png' base.save(temp_loc) image_list.append(imageio.imread(temp_loc)) os.remove(temp_loc) out_loc = f'cache/triggered_{message.id}.gif' imageio.mimsave(out_loc, image_list, fps=30) dfile = discord.File(out_loc) await message.channel.send(file=dfile) try: await resp_msg.delete() except: pass os.remove(out_loc) else: cdembed = discord.Embed(color=0x696969, title=f'?? {target.name} has been put on ice to cool off.') await message.channel.send(embed=cdembed)
def compile_frames_to_gif(frame_dir, gif_file): frames = sorted(glob.glob(os.path.join(frame_dir, "*.png"))) images = [imageio.imread(f) for f in frames] imageio.mimsave(gif_file, images, duration=0.1) return gif_file
def __init__(self, img, ismask=False, transparent=True, fromalpha=False, duration=None): # yapf: disable VideoClip.__init__(self, ismask=ismask, duration=duration) if isinstance(img, str): img = imread(img) if len(img.shape) == 3: # img is (now) a RGB(a) numpy array if img.shape[2] == 4: if fromalpha: img = 1.0 * img[:, :, 3] / 255 elif ismask: img = 1.0 * img[:, :, 0] / 255 elif transparent: self.mask = ImageClip( 1.0 * img[:, :, 3] / 255, ismask=True) img = img[:, :, :3] elif ismask: img = 1.0 * img[:, :, 0] / 255 # if the image was just a 2D mask, it should arrive here # unchanged self.make_frame = lambda t: img self.size = img.shape[:2][::-1] self.img = img
def create_gif(n_images, source_directory, output_name, duration): images = [] for dp_i in range(n_images): images.append(imageio.imread('%s/%06i.png' % (source_directory, dp_i) ) ) output_file = '%s.gif' % ( output_name) imageio.mimsave(output_file, images, duration=duration)
def save_gif(filenames, filepath, duration): images = [] for filename in filenames: images.append(imageio.imread(filename)) kargs = { 'duration': duration } imageio.mimsave(filepath, images, 'GIF', **kargs)
def create_gif(filenames, duration=DURATION): images = [] for filename in filenames: images.append(imageio.imread(filename)) imageio.mimsave(OUT_GIF, images, duration=duration)
def _execute_pipeline_on_image(self, input_data): if input_data['img'].ndim == 3: # It *appears* imageio imread returns RGB or RGBA, not BGR...confirmed using a blue # filled rectangle that imageio is indeed RGB which is opposite of OpenCV's default BGR. # Use RGB consistently everywhere. if input_data['img'].shape[-1] == 4: input_data['gray'] = cv2.cvtColor(input_data['img'], cv2.COLOR_RGBA2GRAY) print("Input image seems to be 4-channel RGBA. Creating 3-channel RGB version") input_data['img'] = cv2.cvtColor(input_data['img'], cv2.COLOR_RGBA2RGB) else: input_data['gray'] = cv2.cvtColor(input_data['img'], cv2.COLOR_RGB2GRAY) elif input_data['img'].ndim == 2: # If input is a grayscale image, it'll have just 2 dimensions, # but Darkflow code expects 3 dimensions. So always keep 'img' a 3 dimension # image no matter what. print("Input image is grayscale. Creating RGB version") input_data['gray'] = input_data['img'].copy() input_data['img'] = cv2.cvtColor(input_data['img'], cv2.COLOR_GRAY2RGB) else: raise "Unknown image format " + input_data['img'].shape print("Input image:", input_data['img'].shape) print("Grayscale image:", input_data['gray'].shape) for comp in self.components: print("Executing %s on %s frame %d" % (comp.name, input_data['file'], input_data.get('frame', 0))) comp_outputs = comp.execute(input_data, self.input_directory, self.output_directory) # At each stage of the pipeline, collect the component's outputs # and add them to the input data so that they're available for # downstream components. input_data[comp.name] = comp_outputs # Release the image arrays. input_data['img'] = None input_data['gray'] = None
def draw2DMovie(solution, t_filming_step, x_start, x_end, y_start, legend, solution_min_value, solution_max_value, t_grid_step): #??????????, ?????????????? ????? ???? ?????(????? ??? ??????????) time_marker_length = len(str(t_filming_step)) #!!!????? ?????????, ????? ?????? x ? ????? ?????? y ?? ????? ???????? ????? x_slice_value = 3 y_slice_value = -1 y_end = 0 #???? ???????? ?? ?????, ??????? ???????? ?????? ? ???????? ????????? ??????: #1: ????? ???? ???? ?? ??????? npArray = np.array(solution[0]) #2: ???? ?????? ?? ???? M = len(npArray) x_step = (x_end - x_start) / M x = np.arange(x_start,x_end,x_step) x_slice_index = int((x_slice_value - x_start) / x_step) + 1 #3: ???? ?????? ?? ?????? M = len(npArray[0]) y_step = (0 - y_start) / M y = np.arange(y_start,y_end,y_step) y_slice_index = int((y_slice_value - y_start) / y_step) + 1 #??????? ?????, ???? ?? ?? ?????????? if not os.path.exists('img'): os.makedirs('img') #??????? ????? ?? ?????????? img\ ????? ????????? ????????. files = glob.glob('img' + os.sep + '*') for f in files: os.remove(f) #???? ???????????? ???, ??????, ?? ?????? ? ????, ??? ????? ???????? ???????? ??????? ???????????? ?? ?????. #???????????? ????????????? ???? ?? ?????????? ? ?????. #?????????? ?? ????? ????? ?????? ??? ????? ??????. # absolute_solution_minimum = solution_min_value # absolute_solution_maximum = solution_max_value #???????? ????????? ?????? ?? ??????? ? ?????. for i in range(0, solution.shape[0], t_filming_step): #???? ???????????? ???, ?????? ?? ?????? ? ????????? ????. ???????????? ????????????? ???? ?? ?????????? ????? ????? ?????? #?????????? ?? ????? ????? ??????????? ???????? ??? ??????? ????? absolute_solution_minimum = np.min(np.min(solution[i])) absolute_solution_maximum = np.max(np.max(solution[i])) draw2DSlice(solution[i], i * t_grid_step, x_start, x_end, y_start, legend, absolute_solution_minimum, absolute_solution_maximum, time_marker_length) #?????? ????? ?? ??????????? ????? img\, ????????? ?? ???? ??. images = [] filenames = sorted(fn for fn in os.listdir(path='img' + os.sep) if fn.endswith('s.png')) for filename in filenames: tmp = imageio.imread('img' + os.sep + filename) images.append(tmp) imageio.mimsave('img' + os.sep + legend + ' movie.gif', images, duration = 0.2)