我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用skimage.io()。
def load_image_array_flowers(image_file, image_size): img = skimage.io.imread(image_file) # GRAYSCALE if len(img.shape) == 2: img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8') img_new[:,:,0] = img img_new[:,:,1] = img img_new[:,:,2] = img img = img_new img_resized = skimage.transform.resize(img, (image_size, image_size)) # FLIP HORIZONTAL WIRH A PROBABILITY 0.5 if random.random() > 0.5: img_resized = np.fliplr(img_resized) return img_resized.astype('float32')
def load_image(path): # load image img = skimage.io.imread(path) img = img / 255.0 assert (0 <= img).all() and (img <= 1.0).all() # print "Original Image Shape: ", img.shape # we crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] # resize to 224, 224 resized_img = skimage.transform.resize(crop_img, (224, 224)) return resized_img # returns the top1 string
def load_image2(path, height=None, width=None): # load image img = skimage.io.imread(path) img = img / 255.0 if height is not None and width is not None: ny = height nx = width elif height is not None: ny = height nx = img.shape[1] * ny / img.shape[0] elif width is not None: nx = width ny = img.shape[0] * nx / img.shape[1] else: ny = img.shape[0] nx = img.shape[1] return skimage.transform.resize(img, (ny, nx))
def loadImg(fn,enc,dtype='float'): """Loads image from filename fn with encoding enc and returns it as with given dtype. Args: fn (str): File path. enc (str): Image encoding, e.g. 'uint16'. Keyword Args: dtype (str): Datatype of pixels of returned image. Returns: numpy.ndarray: Loaded image. """ #Load image img = skimage.io.imread(fn).astype(enc) #Getting img values img=img.real img=img.astype(dtype) return img
def flowList(xFileNames, yFileNames): ''' (x/y)fileNames: List of the fileNames in order to get the flows from ''' frameList = [] if (len(xFileNames) != len(yFileNames)): print 'XFILE!=YFILE ERROR: In', xFileNames[0] for i in range(0, min(len(xFileNames), len(yFileNames))): imgX = io.imread(xFileNames[i]) imgY = io.imread(yFileNames[i]) frameList.append(np.dstack((imgX, imgY))) frameList = np.array(frameList) return frameList
def mandelbrot_color(matrix, output_file_name): """Generates a color version of the Mandelbrot Set Writes its output file to output_file_name Args: matrix: np.array, 2D array representing the mandelbrot set output_file_name: string, filename to write image to """ # I wasn't quite sure on how to do the coloring, so I just interpolated # between two colors: color1 = np.array([[.2], [.2], [.8]]) color2 = np.array([[1], [.2], [.5]]) color_img = np.zeros((matrix.shape[0], matrix.shape[1], 3)) color_img[:, :, 0] = color1[0] + matrix[:, :] * (color2[0] - color1[0]) color_img[:, :, 1] = color1[1] + matrix[:, :] * (color2[1] - color1[1]) color_img[:, :, 2] = color1[2] + matrix[:, :] * (color2[2] - color1[2]) print("\nWriting image to:", output_file_name) skimage.io.imsave(output_file_name, color_img)
def write_img(out_img, out_filename, do_clip=True): """Writes out_img to out_filename """ if use_4channel and len(out_img.shape) == 3 and out_img.shape[2] == 4: out_img = out_img[:,:,:3] assert out_img is not None, 'expected out_img to not be None' out_img = numpy.clip(out_img, 0, 1) if do_clip else out_img if is_pypy: out_img = numpy.asarray(out_img*255, 'uint8') if len(out_img.shape) == 2: mode = 'L' elif len(out_img.shape) == 3: if out_img.shape[2] == 3: mode = 'RGB' elif out_img.shape[2] == 4: mode = 'RGBA' else: raise ValueError('unknown color image mode') else: raise ValueError('unknown number of dimensions for image') I = Image.frombytes(mode, (out_img.shape[1], out_img.shape[0]), out_img.tobytes()) I.save(out_filename) else: try: skimage.io.imsave(out_filename, out_img) except: print('Caught exception while saving to {}: image shape is {}, min: {}, max: {}'.format(out_filename, out_img.shape, out_img.min(), out_img.max())) raise
def load_image(path, size=224): # load image img = skimage.io.imread(path) img = img / 255.0 assert (0 <= img).all() and (img <= 1.0).all() # print "Original Image Shape: ", img.shape # we crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] # resize to 224, 224 resized_img = skimage.transform.resize(crop_img, (size, size)) return resized_img # returns the top1 string
def load_image(path): # Load image [height, width, depth] img = skimage.io.imread(path) / 255.0 assert (0 <= img).all() and (img <= 1.0).all() # Crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) shape = list(img.shape) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] resized_img = skimage.transform.resize(crop_img, (shape[0], shape[1])) return resized_img, shape # Return a resized numpy array of an image specified by its path
def load_image2(path, height=None, width=None): # Load image img = skimage.io.imread(path) / 255.0 if height is not None and width is not None: ny = height nx = width elif height is not None: ny = height nx = img.shape[1] * ny / img.shape[0] elif width is not None: nx = width ny = img.shape[0] * nx / img.shape[1] else: ny = img.shape[0] nx = img.shape[1] return skimage.transform.resize(img, (ny, nx)) # Render the generated image given a tensorflow session and a variable image (x)
def load_image(path): # load image img = skimage.io.imread(path) img = img / 255.0 assert (0 <= img).all() and (img <= 1.0).all() # print "Original Image Shape: ", img.shape # we crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] # resize to 224, 224 resized_img = skimage.transform.resize(crop_img, (224, 224)) if len(resized_img.shape)<3: resized_img = skimage.color.gray2rgb(resized_img) return resized_img # returns the top1 string
def load_image_array(image_file, image_size): img = skimage.io.imread(image_file) # GRAYSCALE if len(img.shape) == 2: img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8') img_new[:,:,0] = img img_new[:,:,1] = img img_new[:,:,2] = img img = img_new img_resized = skimage.transform.resize(img, (image_size, image_size)) # FLIP HORIZONTAL WIRH A PROBABILITY 0.5 if random.random() > 0.5: img_resized = np.fliplr(img_resized) return img_resized.astype('float32')
def load_image(path, height=None, width=None): img = skimage.io.imread(path) if len(img.shape) == 2: img = skimage.color.gray2rgb(img) img = img / 255.0 if height is not None and width is not None: ny = height nx = width elif height is not None: ny = height nx = img.shape[1] * ny / img.shape[0] elif width is not None: nx = width ny = img.shape[0] * nx / img.shape[1] else: ny = img.shape[0] nx = img.shape[1] return skimage.transform.resize(img, (ny, nx))
def imread(path): return skimage.io.imread(path)
def imwrite(im, path): skimage.io.imsave(path, im)
def load_image_array(image_file, image_size, image_id, data_dir='Data/datasets/mscoco/train2014', mode='train'): img = None if os.path.exists(image_file): #print('found' + image_file) img = skimage.io.imread(image_file) else: print('notfound' + image_file) img = skimage.io.imread('http://mscoco.org/images/%d' % (image_id)) img_path = os.path.join(data_dir, 'COCO_%s2014_%.12d.jpg' % ( mode, image_id)) skimage.io.imsave(img_path, img) # GRAYSCALE if len(img.shape) == 2: img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8') img_new[:,:,0] = img img_new[:,:,1] = img img_new[:,:,2] = img img = img_new img_resized = skimage.transform.resize(img, (image_size, image_size)) # FLIP HORIZONTAL WIRH A PROBABILITY 0.5 if random.random() > 0.5: img_resized = np.fliplr(img_resized) return img_resized.astype('float32')
def load_image_inception(image_file, image_size=128): img = skimage.io.imread(image_file) # GRAYSCALE if len(img.shape) == 2: img_new = np.ndarray((img.shape[0], img.shape[1], 3), dtype='uint8') img_new[:, :, 0] = img img_new[:, :, 1] = img img_new[:, :, 2] = img img = img_new if image_size != 0: img = skimage.transform.resize(img, (image_size, image_size), mode='reflect') return img.astype('int32')
def test(): img = skimage.io.imread("./test_data/starry_night.jpg") ny = 300 nx = img.shape[1] * ny / img.shape[0] img = skimage.transform.resize(img, (ny, nx)) skimage.io.imsave("./test_data/test/output.jpg", img)
def saveImg(img,fn,enc="uint16",scale=True,maxVal=None): """Saves image as tif file. ``scale`` triggers the image to be scaled to either the maximum range of encoding or ``maxVal``. See also :py:func:`scaleToEnc`. Args: img (numpy.ndarray): Image to save. fn (str): Filename. Keyword Args: enc (str): Encoding of image. scale (bool): Scale image. maxVal (int): Maximum value to which image is scaled. Returns: str: Filename. """ #Fill nan pixels with 0 img=np.nan_to_num(img) #Scale img if scale: img=scaleToEnc(img,enc,maxVal=maxVal) else: #Convert to encoding img=img.astype(enc) skimage.io.imsave(fn,img) return fn
def check_files(image_dir): print("Checking image files in %s" %(image_dir)) files = os.listdir(image_dir) images = [os.path.join(image_dir, f) for f in files if f.lower().endswith('.jpg')] good_imgs = [] for img in images: try: x = skimage.img_as_float(skimage.io.imread(img)).astype(np.float32) good_imgs.append(img) except: print("Image %s is corrupted and will be removed." %(img)) os.remove(img) good_files = [img.split(os.sep)[-1] for img in good_imgs] return good_files
def __init__(self, deploy=vgg_deploy, model=vgg_model, mean=vgg_mean, scale_dim=[224, 224], image_dim=[224, 224], isotropic=False): caffe.set_mode_gpu() caffe.Net.__init__(self, deploy, model, caffe.TEST) self.scale_dim = np.array(scale_dim) self.image_dim = np.array(image_dim) self.isotropic = isotropic self.transformer = caffe.io.Transformer({'data':self.blobs['data'].data.shape}) self.transformer.set_transpose('data', (2,0,1)) self.transformer.set_mean('data', np.load(mean).mean(1).mean(1)) self.transformer.set_raw_scale('data', 255) self.transformer.set_channel_swap('data', (2,1,0))
def load_image(self, image_dir): image = skimage.img_as_float(skimage.io.imread(image_dir)).astype(np.float32) assert image.ndim == 2 or image.ndim == 3 if image.ndim == 2: image = image[:, :, np.newaxis] image = np.tile(image, (1, 1, 3)) elif image.shape[2] > 3: image = image[:, :, :3] return image
def mandelbrot_gray(matrix, output_file_name): """Generates a grayscale version of the Mandelbrot Set Writes its output file to output_file_name Args: matrix: np.array, 2D array representing the mandelbrot set output_file_name: string, filename to write image to """ print("\nWriting image to:", output_file_name) skimage.io.imsave(output_file_name, matrix)
def read_img(in_filename, grayscale=False, extra_info={}): """Returns the image saved at in_filename as a numpy array. If grayscale is True, converts from 3D RGB image to 2D grayscale image. """ if is_pypy: ans = Image.open(in_filename) height = ans.height width = ans.width channels = len(ans.getbands()) if ans.mode == 'I': numpy_mode = 'uint32' maxval = 65535.0 elif ans.mode in ['L', 'RGB', 'RGBA']: numpy_mode = 'uint8' maxval = 255.0 else: raise ValueError('unknown mode') ans = numpy.fromstring(ans.tobytes(), numpy_mode).reshape((height, width, channels)) ans = ans/maxval if grayscale and (len(ans.shape) == 3 and ans.shape[2] == 3): ans = ans[:,:,0]*0.2125 + ans[:,:,1]*0.7154 + ans[:,:,2]*0.0721 if len(ans.shape) == 3 and ans.shape[2] == 1: ans = ans[:,:,0] return ans else: ans = skimage.io.imread(in_filename) if ans.dtype == numpy.int32: # Work around scikit-image bug #1680 ans = numpy.asarray(ans, numpy.uint16) ans = skimage.img_as_float(ans) if grayscale: ans = skimage.color.rgb2gray(ans) # print('here', use_4channel, len(ans.shape) == 3, ans.shape[2] == 3) if use_4channel and len(ans.shape) == 3 and ans.shape[2] == 3: ans = numpy.dstack((ans,) + (numpy.ones((ans.shape[0], ans.shape[1], 1)),)) extra_info['originally_3channel'] = True return ans
def __enter__(self): if not self.verbose: self.old_stdout = sys.stdout self.old_stderr = sys.stderr sys.stdout = self.stdout = io.StringIO() sys.stderr = self.stderr = io.StringIO()
def load_images(image_files, vgg, pl_images): dataset = np.ndarray(shape=(len(image_files), feat_len), dtype=np.float32) image_index = 0 for image in image_files: try: if not tf.gfile.Exists(image): tf.logging.fatal('File does not exist %s', image) image_data = skimage.io.imread(image) image_data = image_data / 255.0 batch = np.ndarray(shape=(1, image_data.shape[0], image_data.shape[1], image_data.shape[2]), dtype=np.float32) batch[0, :, :, :] = image_data feed_dict = {pl_images: batch} with tf.Session() as sess: with tf.device("/cpu:0"): feat = sess.run(vgg.conv5_4, feed_dict=feed_dict) feat.resize(feat_len,refcheck=False) dataset[image_index, :] = feat image_index += 1 except IOError as e: print('Could not read:', image, ':', e, '- it\'s ok, skipping.') dataset = dataset[0:image_index, :] print('Full dataset tensor:', dataset.shape) return dataset
def load_image(path, image_h, image_w, zoom=False): # load image img = skimage.io.imread(path) if img.ndim < 3: img = skimage.color.gray2rgb(img) # we crop image from center ratio = float(image_h) / image_w height = int(img.shape[0]) width = int(img.shape[1]) yy = 0 xx = 0 if height > width * ratio: #too tall yy = int(height - width * ratio) // 2 height = int(width * ratio) else: # too wide xx = int(width - height / ratio) // 2 width = int(height / ratio) if zoom: yy += int(height / 6) xx += int(height / 6) height = int(height * 2/ 3) width = int(width * 2 / 3) crop_img = img[yy: yy + height, xx: xx + width] # resize resized_img = skimage.transform.resize(crop_img, (image_h, image_w), preserve_range=True) centered_img = resized_img - MEAN_VALUES return centered_img
def write_image(path, image, verbose=False): img = image[0] + MEAN_VALUES if verbose: print("%f - %f" % (np.min(img), np.max(img))) img = np.clip(img, 0, 255).astype('uint8') skimage.io.imsave(path, img) # returns the top1 string
def get_all_test_data(im_list, la_list): images = [] labels = [] index = 0 for im_filename, la_filename in zip(im_list, la_list): im = np.array(skimage.io.imread(im_filename), np.float32) im = im[np.newaxis] la = skimage.io.imread(la_filename) la = la[np.newaxis] la = la[...,np.newaxis] images.append(im) labels.append(la) return images, labels
def load_image(path): # load image img = skimage.io.imread(path) img = img / 255.0 assert (0 <= img).all() and (img <= 1.0).all() # print "Original Image Shape: ", img.shape # we crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] # resize to 299, 299 resized_img = skimage.transform.resize(crop_img, (299, 299)) return resized_img
def load_image(path): # load image img = skimage.io.imread(path) img = img / 255.0 assert (0 <= img).all() and (img <= 1.0).all() # print "Original Image Shape: ", img.shape # we crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] # resize to 224, 224 resized_img = skimage.transform.resize(crop_img, (224, 224)) return resized_img
def load_image(path): # load image img = skimage.io.imread(path) img = img / 255.0 assert (0 <= img).all() and (img <= 1.0).all() # print "Original Image Shape: ", img.shape # we crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] # resize to 224, 224 resized_img = skimage.transform.resize(crop_img, (299, 299)) return resized_img
def get_saliency_ft(img): # Saliency map calculation based on: if isinstance(img, str): img = skimage.io.imread(img) img_rgb = img_as_float(img) img_lab = skimage.color.rgb2lab(img_rgb) mean_val = np.mean(img_rgb, axis=(0, 1)) kernel_h = (1.0 / 16.0) * np.array([[1, 4, 6, 4, 1]]) kernel_w = kernel_h.transpose() blurred_l = scipy.signal.convolve2d(img_lab[:, :, 0], kernel_h, mode='same') blurred_a = scipy.signal.convolve2d(img_lab[:, :, 1], kernel_h, mode='same') blurred_b = scipy.signal.convolve2d(img_lab[:, :, 2], kernel_h, mode='same') blurred_l = scipy.signal.convolve2d(blurred_l, kernel_w, mode='same') blurred_a = scipy.signal.convolve2d(blurred_a, kernel_w, mode='same') blurred_b = scipy.signal.convolve2d(blurred_b, kernel_w, mode='same') im_blurred = np.dstack([blurred_l, blurred_a, blurred_b]) sal = np.linalg.norm(mean_val - im_blurred, axis=2) sal_max = np.max(sal) sal_min = np.min(sal) sal = 255 * ((sal - sal_min) / (sal_max - sal_min)) return sal
def saveLastBatchResults(self, outputImages, isTrain=True): """Saves the results of last retrieved image batch Args: outputImages: 4D Numpy array [batchSize, H, W, numClasses] isTrain: If the last batch was training batch Returns: None """ if isTrain: imageNames = [self.imageList[index] for index in self.indices] else: imageNames = [self.imageListTest[index] for index in self.indices] # Iterate over each image name and save the results for i in xrange(0, self.options.batchSize): imageName = imageNames[i].split('/') imageName = imageName[-1] if isTrain: imageName = self.options.imagesOutputDirectory + '/' + 'train_' + imageName[:-4] + '_prob' + imageName[-4:] else: imageName = self.options.imagesOutputDirectory + '/' + 'test_' + imageName[:-4] + '_prob' + imageName[-4:] # print(imageName) # Save foreground probability im = np.squeeze(outputImages[i, :, :, 1] * 255) im = im.astype(np.uint8) # Convert image from float to unit8 for saving skimage.io.imsave(imageName, im)
def getImage(datapath, imageID, purpose='train'): name_3 = str(imageID) name_2 = '0' * (12-len(name_3)) name_1 = 'COCO_' + purpose + '2014_' fileName = name_1 + name_2 + name_3 + '.jpg' filepath = join(datapath,fileName) img = skimage.io.imread(filepath) return(img)
def show_image(img): skimage.io.imshow(img) skimage.io.show() # [height, width, depth]
def load_image(path): # load image img = skimage.io.imread(path) img = img / 255.0 assert (0 <= img).all() and (img <= 1.0).all() print( "Original Image Shape: ", img.shape) # we crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] # resize to 224, 224 resized_img = skimage.transform.resize(crop_img, (256, 256)) print( "Resize Image Shape: ", resized_img.shape) return resized_img