本文整理汇总了Python中scipy.ndimage.imread方法的典型用法代码示例。如果您正苦于以下问题:Python ndimage.imread方法的具体用法?Python ndimage.imread怎么用?Python ndimage.imread使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.ndimage
的用法示例。
在下文中一共展示了ndimage.imread方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: convert_image
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def convert_image(self, filename):
pic = img.imread(filename)
# Set FFT size to be double the image size so that the edge of the spectrum stays clear
# preventing some bandfilter artifacts
self.NFFT = 2*pic.shape[1]
# Repeat image lines until each one comes often enough to reach the desired line time
ffts = (np.flipud(np.repeat(pic[:, :, 0], self.repetitions, axis=0) / 16.)**2.) / 256.
# Embed image in center bins of the FFT
fftall = np.zeros((ffts.shape[0], self.NFFT))
startbin = int(self.NFFT/4)
fftall[:, startbin:(startbin+pic.shape[1])] = ffts
# Generate random phase vectors for the FFT bins, this is important to prevent high peaks in the output
# The phases won't be visible in the spectrum
phases = 2*np.pi*np.random.rand(*fftall.shape)
rffts = fftall * np.exp(1j*phases)
# Perform the FFT per image line, then concatenate them to form the final signal
timedata = np.fft.ifft(np.fft.ifftshift(rffts, axes=1), axis=1) / np.sqrt(float(self.NFFT))
linear = timedata.flatten()
linear = linear / np.max(np.abs(linear))
return linear
示例2: encoder
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def encoder(in_queue, threshold, generated_masks, time_counts):
while True:
img_name, mask_img_path = in_queue.get()
if img_name is None:
break
t0 = time.clock()
mask_img = ndimage.imread(mask_img_path, mode='L')
mask_img[mask_img <= threshold] = 0
mask_img[mask_img > threshold] = 1
time_counts['time_read'].append(time.clock() - t0)
t0 = time.clock()
rle = rle_encode(mask_img)
time_counts['time_rle'].append(time.clock() - t0)
t0 = time.clock()
rle_string = rle_to_string(rle)
time_counts['time_stringify'].append(time.clock() - t0)
generated_masks.append((img_name, rle_string))
示例3: crawl_directory
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def crawl_directory(directory, augment_with_rotations=False, first_label=0):
"""Crawls data directory and returns stuff."""
label_idx = first_label
images = []
labels = []
info = []
# traverse root directory
for root, _, files in os.walk(directory):
logging.info('Reading files from %s', root)
for file_name in files:
full_file_name = os.path.join(root, file_name)
img = imread(full_file_name, flatten=True)
for idx, angle in enumerate([0, 90, 180, 270]):
if not augment_with_rotations and idx > 0:
break
images.append(imrotate(img, angle))
labels.append(label_idx + idx)
info.append(full_file_name)
if len(files) == 20:
label_idx += 4 if augment_with_rotations else 1
return images, labels, info
示例4: load_images
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def load_images(img_dims):
"""Load all images into a dictionary with filename as the key and numpy image array as the value."""
image_list = {}
for root, dirnames, filenames in os.walk(config.path_img):
for filename in filenames:
if re.search("\.(jpg|jpeg|png|bmp|tiff)$", filename):
filepath = os.path.join(root, filename)
try:
image = ndimage.imread(filepath, mode="RGB")
except OSError:
print('Could not load image {}'.format(filepath))
image_resized = misc.imresize(image, img_dims)
if np.random.random() > 0.5:
# Flip horizontally with probability 50%
image_resized = np.fliplr(image_resized)
image_list[filename.split('.')[0]] = image_resized
print('Loaded {:,} images from disk'.format(len(image_list)))
return image_list
示例5: test_imread
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def test_imread():
lp = os.path.join(os.path.dirname(__file__), 'dots.png')
with suppress_warnings() as sup:
# PIL causes a Py3k ResourceWarning
sup.filter(message="unclosed file")
sup.filter(DeprecationWarning)
img = ndi.imread(lp, mode="RGB")
assert_array_equal(img.shape, (300, 420, 3))
with suppress_warnings() as sup:
# PIL causes a Py3k ResourceWarning
sup.filter(message="unclosed file")
sup.filter(DeprecationWarning)
img = ndi.imread(lp, flatten=True)
assert_array_equal(img.shape, (300, 420))
with open(lp, 'rb') as fobj:
with suppress_warnings() as sup:
sup.filter(DeprecationWarning)
img = ndi.imread(fobj, mode="RGB")
assert_array_equal(img.shape, (300, 420, 3))
示例6: load_images_from_jpg
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def load_images_from_jpg(subset="train", downsample_factor=None, normalise=True, from_ram=False):
if from_ram:
pattern = "/dev/shm/images_%s_rev1/*.jpg"
else:
pattern = "data/raw/images_%s_rev1/*.jpg"
paths = glob.glob(pattern % subset)
paths.sort() # alphabetic ordering is used everywhere.
for path in paths:
# img = ndimage.imread(path)
img = skimage.io.imread(path)
if normalise:
img = img.astype('float32') / 255.0 # normalise and convert to float
if downsample_factor is None:
yield img
else:
yield img[::downsample_factor, ::downsample_factor]
示例7: __getitem__
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def __getitem__(self, idx):
if self.train:
img_path, gt_path = self.train_set_path[idx]
img = imread(img_path)
img = img[0:self.nRow, 0:self.nCol]
img = np.atleast_3d(img).transpose(2, 0, 1).astype(np.float32)
img = (img - img.min()) / (img.max() - img.min())
img = torch.from_numpy(img).float()
gt = imread(gt_path)[0:self.nRow, 0:self.nCol]
gt = np.atleast_3d(gt).transpose(2, 0, 1)
gt = gt / 255.0
gt = torch.from_numpy(gt).float()
return img, gt
示例8: read_image
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def read_image(path, max_intensity):
image = nd.imread(path, mode="L")
image = np.asarray(image, dtype=np.float32) / 255.0
img_min, img_max = image.min(), image.max()
if img_min != img_max:
if img_min > 0.0:
image -= img_min
if img_max > 0.0:
image /= img_max
if max_intensity < 1.0:
image *= max_intensity
else:
if img_max > max_intensity:
image = np.ones_like(image) * max_intensity
return image
示例9: LoadImgAsPoints
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def LoadImgAsPoints(self, fn):
if(fn in self.image_points_cache):
return self.image_points_cache[fn]
I = imread(fn, flatten=True)
I = np.asarray(imresize(I, size=self.image_size), dtype=np.float32)
I[I<255] = 0
I = np.array(I, dtype=bool)
I = np.logical_not(I)
(row, col) = I.nonzero()
D = np.array([row, col])
D = np.transpose(D)
D = D.astype(float)
n = D.shape[0]
mean = np.mean(D, axis=0)
for i in range(n):
D[i, :] = D[i, :] - mean
self.image_points_cache[fn] = D
return D
示例10: omniglot_folder_to_NDarray
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def omniglot_folder_to_NDarray(path_im):
alphbts = os.listdir(path_im)
ALL_IMGS = []
for alphbt in alphbts:
chars = os.listdir(os.path.join(path_im, alphbt))
for char in chars:
img_filenames = os.listdir(os.path.join(path_im, alphbt, char))
char_imgs = []
for img_fn in img_filenames:
fn = os.path.join(path_im, alphbt, char, img_fn)
I = imread(fn)
I = np.invert(I)
char_imgs.append(I)
ALL_IMGS.append(char_imgs)
return np.array(ALL_IMGS)
示例11: save
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def save(fp, image, quality=75):
image_jpg = compress_to_jpg(image, quality=quality)
image_jpg_decompressed = decompress_jpg(image_jpg)
# If the image file already exists and is (practically) identical,
# then don't save it again to avoid polluting the repository with tons
# of image updates.
# Not that we have to compare here the results AFTER jpg compression
# and then decompression. Otherwise we compare two images of which
# image (1) has never been compressed while image (2) was compressed and
# then decompressed.
if os.path.isfile(fp):
image_saved = ndimage.imread(fp, mode="RGB")
#print("arrdiff", arrdiff(image_jpg_decompressed, image_saved))
same_shape = (image_jpg_decompressed.shape == image_saved.shape)
d_avg = arrdiff(image_jpg_decompressed, image_saved) if same_shape else -1
if same_shape and d_avg <= 1.0:
print("[INFO] Did not save image '%s', because the already saved image is basically identical (d_avg=%.8f)" % (fp, d_avg,))
return
else:
print("[INFO] Saving image '%s'..." % (fp,))
with open(fp, "w") as f:
f.write(image_jpg)
示例12: quokka
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def quokka(size=None):
"""
Returns an image of a quokka as a numpy array.
Parameters
----------
size : None or float or tuple of two ints, optional(default=None)
Size of the output image. Input into scipy.misc.imresize.
Usually expected to be a tuple (H, W), where H is the desired height
and W is the width. If None, then the image will not be resized.
Returns
-------
img : (H,W,3) ndarray
The image array of dtype uint8.
"""
img = ndimage.imread(QUOKKA_FP, mode="RGB")
if size is not None:
img = misc.imresize(img, size)
return img
示例13: eval_sequence
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def eval_sequence(gt_folder, recog_folder):
seq = gt_folder.split("/")[-7] + "_" + gt_folder.split("/")[-5]
gt_files = sorted(glob.glob(gt_folder + "/*.jpg"))
#checks
#if not gt_files[0].endswith("00001.jpg"):
# print "does not start with 00001.jpg!", gt_files[0]
#indices = [int(f.split("/")[-1][:-4]) for f in gt_files]
#if not (numpy.diff(indices) == 10).all():
# print "no spacing of 10:", gt_files
gt_files = gt_files[1:]
recog_folder_seq = recog_folder + seq + "/"
print(recog_folder_seq, end=' ')
recog_files = [gt_file.replace(gt_folder, recog_folder_seq).replace(".jpg", ".png") for gt_file in gt_files]
ious = []
for gt_file, recog_file in zip(gt_files, recog_files):
gt = imread(gt_file) / 255
recog = imread(recog_file) / 255
iou = compute_iou_for_binary_segmentation(recog, gt)
ious.append(iou)
return numpy.mean(ious)
示例14: eval_sequence
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def eval_sequence(gt_folder, recog_folder):
seq = gt_folder.split("/")[-7] + "_" + gt_folder.split("/")[-5]
gt_files = sorted(glob.glob(gt_folder + "/*.jpg"))
gt_files = gt_files[1:]
recog_folder_seq = recog_folder + seq + "/"
#for full dataset
recog_files = []
for gt_file in gt_files:
idx = int(gt_file.split("/")[-1].replace(".jpg", ""))
ending = "frame%04d.png" % idx
recog_file = recog_folder_seq + ending
recog_files.append(recog_file)
ious = []
for gt_file, recog_file in zip(gt_files, recog_files):
gt = imread(gt_file) / 255
recog = imread(recog_file) / 255
iou = compute_iou_for_binary_segmentation(recog, gt)
ious.append(iou)
return numpy.mean(ious)
示例15: run_multiclass_crf
# 需要导入模块: from scipy import ndimage [as 别名]
# 或者: from scipy.ndimage import imread [as 别名]
def run_multiclass_crf(seq, fn, posteriors, softmax_scale, sxy1, compat1, sxy2, compat2, srgb):
im_fn = DAVIS2017_DIR + "JPEGImages/480p/" + seq + "/" + fn.replace(".pickle", ".jpg")
im = imread(im_fn)
nlabels = posteriors.shape[-1]
im = numpy.ascontiguousarray(im)
pred = numpy.ascontiguousarray(posteriors.swapaxes(0, 2).swapaxes(1, 2))
d = dcrf.DenseCRF2D(im.shape[1], im.shape[0], nlabels) # width, height, nlabels
unaries = unary_from_softmax(pred, scale=softmax_scale)
d.setUnaryEnergy(unaries)
d.addPairwiseGaussian(sxy=sxy1, compat=compat1)
d.addPairwiseBilateral(sxy=sxy2, srgb=srgb, rgbim=im, compat=compat2)
processed = d.inference(12)
res = numpy.argmax(processed, axis=0).reshape(im.shape[:2])
return res