当前位置: 首页>>代码示例>>Python>>正文


Python io.imread方法代码示例

本文整理汇总了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])) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:18,代码来源:nstyle.py

示例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) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:23,代码来源:mxnet_predict_example.py

示例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]) 
开发者ID:yiling-chen,项目名称:view-finding-network,代码行数:24,代码来源:vfn_eval.py

示例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 
开发者ID:soubhiksanyal,项目名称:RingNet,代码行数:21,代码来源:demo.py

示例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 
开发者ID:nicholastoddsmith,项目名称:poeai,代码行数:21,代码来源:Bot.py

示例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 
开发者ID:cosmic-cortex,项目名称:pytorch-UNet,代码行数:20,代码来源:dataset.py

示例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] 
开发者ID:yizt,项目名称:keras-ctpn,代码行数:21,代码来源:image_utils.py

示例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) 
开发者ID:clvrai,项目名称:Representation-Learning-by-Learning-to-Count,代码行数:18,代码来源:ImageNet.py

示例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 
开发者ID:kirumang,项目名称:Pix2Pose,代码行数:20,代码来源:1_1_scene_gen_for_detection_maskrcnn.py

示例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 
开发者ID:GaoangW,项目名称:TNT,代码行数:25,代码来源:tracklet_utils_3c.py

示例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) 
开发者ID:ignacio-rocco,项目名称:weakalign,代码行数:20,代码来源:pf_dataset.py

示例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 
开发者ID:crashmoon,项目名称:Progressive-Generative-Networks,代码行数:21,代码来源:gan_lstm_two.py

示例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 
开发者ID:dalmia,项目名称:WannaPark,代码行数:20,代码来源:secure_camera.py

示例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 
开发者ID:mjendrusch,项目名称:torchsupport,代码行数:25,代码来源:io.py

示例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 
开发者ID:mjendrusch,项目名称:torchsupport,代码行数:25,代码来源:io.py


注:本文中的skimage.io.imread方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。