本文整理汇总了Python中skimage.io.imread方法的典型用法代码示例。如果您正苦于以下问题:Python io.imread方法的具体用法?Python io.imread怎么用?Python io.imread使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类skimage.io
的用法示例。
在下文中一共展示了io.imread方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PreprocessContentImage
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def PreprocessContentImage(path, long_edge):
img = io.imread(path)
logging.info("load the content image, size = %s", img.shape[:2])
factor = float(long_edge) / max(img.shape[:2])
new_size = (int(img.shape[0] * factor), int(img.shape[1] * factor))
resized_img = transform.resize(img, new_size)
sample = np.asarray(resized_img) * 256
# swap axes to make image from (224, 224, 3) to (3, 224, 224)
sample = np.swapaxes(sample, 0, 2)
sample = np.swapaxes(sample, 1, 2)
# sub mean
sample[0, :] -= 123.68
sample[1, :] -= 116.779
sample[2, :] -= 103.939
logging.info("resize the content image to %s", new_size)
return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2]))
示例2: PreprocessImage
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def PreprocessImage(path, show_img=False):
# load image
img = io.imread(path)
print("Original Image Shape: ", img.shape)
# we crop image from center
short_egde = min(img.shape[:2])
yy = int((img.shape[0] - short_egde) / 2)
xx = int((img.shape[1] - short_egde) / 2)
crop_img = img[yy : yy + short_egde, xx : xx + short_egde]
# resize to 224, 224
resized_img = transform.resize(crop_img, (224, 224))
# convert to numpy.ndarray
sample = np.asarray(resized_img) * 255
# swap axes to make image from (224, 224, 3) to (3, 224, 224)
sample = np.swapaxes(sample, 0, 2)
sample = np.swapaxes(sample, 1, 2)
# sub mean
return sample
# Get preprocessed batch (single image batch)
示例3: evaluate_sliding_window
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def evaluate_sliding_window(img_filename, crops):
img = io.imread(img_filename).astype(np.float32)/255
if img.ndim == 2: # Handle B/W images
img = np.expand_dims(img, axis=-1)
img = np.repeat(img, 3, 2)
img_crops = np.zeros((batch_size, 227, 227, 3))
for i in xrange(len(crops)):
crop = crops[i]
img_crop = transform.resize(img[crop[1]:crop[1]+crop[3],crop[0]:crop[0]+crop[2]], (227, 227))-0.5
img_crop = np.expand_dims(img_crop, axis=0)
img_crops[i,:,:,:] = img_crop
# compute ranking scores
scores = sess.run([score_func], feed_dict={image_placeholder: img_crops})
# find the optimal crop
idx = np.argmax(scores[:len(crops)])
best_window = crops[idx]
# return the best crop
return (best_window[0], best_window[1], best_window[2], best_window[3])
示例4: preprocess_image
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def preprocess_image(img_path):
img = io.imread(img_path)
if np.max(img.shape[:2]) != config.img_size:
print('Resizing so the max image size is %d..' % config.img_size)
scale = (float(config.img_size) / np.max(img.shape[:2]))
else:
scale = 1.0#scaling_factor
center = np.round(np.array(img.shape[:2]) / 2).astype(int)
# image center in (x,y)
center = center[::-1]
crop, proc_param = img_util.scale_and_crop(img, scale, center,
config.img_size)
# import ipdb; ipdb.set_trace()
# Normalize image to [-1, 1]
# plt.imshow(crop/255.0)
# plt.show()
crop = 2 * ((crop / 255.) - 0.5)
return crop, proc_param, img
示例5: SplitSave
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def SplitSave(self, p = 'TSD/Train/Images', wp = 'TSD/Train/Split'):
'''
#p: #Dir contains images to split
#wp: #Dir to write split images
'''
c = 0
if not os.path.exists(wp):
os.mkdir(wp)
pdl = np.random.choice([fni for fni in os.listdir(p) if fni.startswith('di')], 32, replace = False)
for i, fn in enumerate(pdl):
print('{:4d}/{:4d}:\t{:s}'.format(i + 1, len(pdl), fn))
#A = imread(os.path.join(p, fn))[0:-14, 1:-1]
#A = self.GetScreen()
#S = self.ts.DivideIntoSubimages(A).astype(np.uint8)
A = imread(os.path.join(p, fn))[0:-12, 4:-4, :]
S = self.ts.DivideIntoSubimages(A).astype(np.uint8)
for i, Si in enumerate(S):
imsave(os.path.join(wp, '{:03d}.png'.format(c)), Si)
c += 1
示例6: __getitem__
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def __getitem__(self, idx):
image_filename = self.images_list[idx]
# read image
image = io.imread(os.path.join(self.input_path, image_filename))
# read mask image
mask = io.imread(os.path.join(self.output_path, image_filename))
# correct dimensions if needed
image, mask = correct_dims(image, mask)
if self.joint_transform:
image, mask = self.joint_transform(image, mask)
if self.one_hot_mask:
assert self.one_hot_mask > 0, 'one_hot_mask must be nonnegative'
mask = torch.zeros((self.one_hot_mask, mask.shape[1], mask.shape[2])).scatter_(0, mask.long(), 1)
return image, mask, image_filename
示例7: load_image
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def load_image(image_path):
"""
加载图像
:param image_path: 图像路径
:return: [h,w,3] numpy数组
"""
image = plt.imread(image_path)
# 灰度图转为RGB
if len(image.shape) == 2:
image = np.expand_dims(image, axis=2)
image = np.tile(image, (1, 1, 3))
elif image.shape[-1] == 1:
image = skimage.color.gray2rgb(image) # io.imread 报ValueError: Input image expected to be RGB, RGBA or gray
# 标准化为0~255之间
if image.dtype == np.float32:
image *= 255
image = image.astype(np.uint8)
# 删除alpha通道
return image[..., :3]
示例8: __init__
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def __init__(self, ids, name='default',
max_examples=None, is_train=True):
self._ids = list(ids)
self.name = name
self.is_train = is_train
if max_examples is not None:
self._ids = self._ids[:max_examples]
file = os.path.join(__IMAGENET_IMG_PATH__, self._ids[0])
try:
imread(file)
except:
raise IOError('Dataset not found. Please make sure the dataset was downloaded.')
log.info("Reading Done: %s", file)
示例9: get_random_background
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def get_random_background(im_height,im_width,backfiles):
back_fn = backfiles[int(random.random()*(len(backfiles)-1))]
back_img = cv2.imread(back_dir+"/"+back_fn)
img_syn = np.zeros( (im_height,im_width,3))
if back_img.ndim != 3:
back_img = skimage.color.gray2rgb(back_img)
back_v = min(back_img.shape[0],img_syn.shape[0])
back_u = min(back_img.shape[1],img_syn.shape[1])
img_syn[:back_v,:back_u]=back_img[:back_v,:back_u]/255
if(img_syn.shape[0]>back_img.shape[0]):
width = min(img_syn.shape[0]-back_v,back_img.shape[0])
img_syn[back_v:back_v+width,:back_u]=back_img[:width,:back_u]/255
if(img_syn.shape[1]>back_img.shape[1]):
height = min(img_syn.shape[1]-back_u,back_img.shape[1])
img_syn[:back_v,back_u:back_u+height]=back_img[:back_v,:height]/255
return img_syn
示例10: hist_feature_extract
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def hist_feature_extract(feature_size, num_patch, max_length, patch_folder):
fea_mat = np.zeros((num_patch,feature_size-4+2))
tracklet_list = os.listdir(patch_folder)
N_tracklet = len(tracklet_list)
cnt = 0
for n in range(N_tracklet):
tracklet_folder = patch_folder+'/'+tracklet_list[n]
patch_list = os.listdir(tracklet_folder)
# get patch list, track_id and fr_id, starts from 1
prev_cnt = cnt
for m in range(len(patch_list)):
# track_id
fea_mat[cnt,0] = n+1
# fr_id
fea_mat[cnt,1] = int(patch_list[m][-8:-4])
patch_list[m] = tracklet_folder+'/'+patch_list[m]
patch_img = imread(patch_list[m])
fea_mat[cnt,2:] = track_lib.extract_hist(patch_img)
#import pdb; pdb.set_trace()
cnt = cnt+1
return fea_mat
示例11: get_image
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def get_image(self,img_name_list,idx):
img_name = os.path.join(self.dataset_path, img_name_list[idx])
image = io.imread(img_name)
# get image size
im_size = np.asarray(image.shape)
# convert to torch Variable
image = np.expand_dims(image.transpose((2,0,1)),0)
image = torch.Tensor(image.astype(np.float32))
image_var = Variable(image,requires_grad=False)
# Resize image using bilinear sampling with identity affine tnf
image = self.affineTnf(image_var).data.squeeze(0)
im_size = torch.Tensor(im_size.astype(np.float32))
return (image, im_size)
示例12: __getitem__
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def __getitem__(self, idx):
image_pos = self.lines.ix[idx, 0]
image = io.imread(image_pos)
image = image.astype(np.float)
h,w = image.shape[:2]
if(h<w):
factor = h/350.0
w = w/factor
h = 350
else:
factor = w/350.0
h = h/factor
w = 350
image = transform.resize(image, (int(h), int(w), 3))
image_id = self.lines.ix[idx, 1]
sample = {'image': image, 'id': image_id}
if self.trans is not None:
sample = self.trans(sample)
return sample
示例13: get_car_image_plate_number
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def get_car_image_plate_number(image_path, image_name):
img = Image(cv2.imread(image_path,0), image_name)
l_carsR = getCarsFromImage(img.img, carClassifier)
for carR in l_carsR:
car = Car(img.img, carR, plateCassifier)
car.setPlateText(processPlateText(car, net))
img.addCar(car)
for car in img.cars:
car.draw()
if(not car.isPlateEmpty()):
plate_number = car.plateText
# imshow(car.carImg)
x, y, w, h = car.carR.x, car.carR.y, car.carR.w, car.carR.h
color_image = imread(image_path)
return color_image[y:y+h, x:x+w], plate_number
示例14: imread
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def imread(path, type='float32'):
"""Reads a given image from file, returning a `Tensor`.
Args:
path (str): path to an image file.
type (str): the desired type of the output tensor, defaults to 'float32'.
"""
reading = True
while reading:
try:
image = io.imread(path)
reading = False
except OSError as e:
if e.errno == 121:
print("Attempting to recover from Remote IO Error ...")
time.sleep(10)
else:
print("Unexpected OSError. Aborting ...")
raise e
image = np.array(image).astype(type)
image = np.transpose(image,(2,0,1))
image = torch.from_numpy(image)
return image
示例15: stackread
# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imread [as 别名]
def stackread(path, type='float32'):
"""Reads a given image from file, returning a `Tensor`.
Args:
path (str): path to an image file.
type (str): the desired type of the output tensor, defaults to 'float32'.
"""
reading = True
while reading:
try:
image = io.imread(path)
reading = False
except OSError as e:
if e.errno == 121:
print("Attempting to recover from Remote IO Error ...")
time.sleep(10)
else:
print("Unexpected OSError. Aborting ...")
raise e
image = np.array(image).astype(type)
image = np.transpose(image,(0,1,2))
image = torch.from_numpy(image)
return image