Python skimage.io.imread() Examples

The following are 30 code examples for showing how to use skimage.io.imread(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module skimage.io , or try the search function .

Example 1
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: nstyle.py    License: Apache License 2.0 6 votes vote down vote up
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])) 
Example 2
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) 
Example 3
Project: view-finding-network   Author: yiling-chen   File: vfn_eval.py    License: GNU General Public License v3.0 6 votes vote down vote up
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]) 
Example 4
Project: RingNet   Author: soubhiksanyal   File: demo.py    License: MIT License 6 votes vote down vote up
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 
Example 5
Project: poeai   Author: nicholastoddsmith   File: Bot.py    License: MIT License 6 votes vote down vote up
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 
Example 6
Project: pytorch-UNet   Author: cosmic-cortex   File: dataset.py    License: MIT License 6 votes vote down vote up
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 
Example 7
Project: keras-ctpn   Author: yizt   File: image_utils.py    License: Apache License 2.0 6 votes vote down vote up
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] 
Example 8
Project: Representation-Learning-by-Learning-to-Count   Author: clvrai   File: ImageNet.py    License: MIT License 6 votes vote down vote up
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) 
Example 9
Project: Pix2Pose   Author: kirumang   File: 1_1_scene_gen_for_detection_maskrcnn.py    License: MIT License 6 votes vote down vote up
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 
Example 10
Project: TNT   Author: GaoangW   File: tracklet_utils_3c.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 11
Project: TNT   Author: GaoangW   File: tracklet_utils_3c.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 12
Project: weakalign   Author: ignacio-rocco   File: pf_dataset.py    License: MIT License 6 votes vote down vote up
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) 
Example 13
Project: weakalign   Author: ignacio-rocco   File: pf_dataset.py    License: MIT License 6 votes vote down vote up
def get_image(self,img_name_list,idx):
        img_name = os.path.join(self.dataset_path, img_name_list.iloc[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) 
Example 14
Project: weakalign   Author: ignacio-rocco   File: pascal_parts_dataset.py    License: MIT License 6 votes vote down vote up
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) 
Example 15
Project: Progressive-Generative-Networks   Author: crashmoon   File: gan_lstm_two.py    License: MIT License 6 votes vote down vote up
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 
Example 16
Project: Progressive-Generative-Networks   Author: crashmoon   File: gan_lstm.py    License: MIT License 6 votes vote down vote up
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 
Example 17
Project: Progressive-Generative-Networks   Author: crashmoon   File: gan_lstm.py    License: MIT License 6 votes vote down vote up
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 
Example 18
Project: Progressive-Generative-Networks   Author: crashmoon   File: gan_lstm_oval.py    License: MIT License 6 votes vote down vote up
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 
Example 19
Project: Progressive-Generative-Networks   Author: crashmoon   File: gan_lstm_oval.py    License: MIT License 6 votes vote down vote up
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 
Example 20
Project: WannaPark   Author: dalmia   File: secure_camera.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 21
Project: torchsupport   Author: mjendrusch   File: io.py    License: MIT License 6 votes vote down vote up
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 
Example 22
Project: torchsupport   Author: mjendrusch   File: io.py    License: MIT License 6 votes vote down vote up
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 
Example 23
Project: COCO-Assistant   Author: ashnair1   File: coco_visualiser.py    License: MIT License 6 votes vote down vote up
def visualise_single(ann, folder, img_filename):
    if folder not in ['train', 'val', 'test']:
        raise AssertionError('Folder not in ["train", "val", "test"]')
    # Get image id and image filename mapping dict
    id_fn_dict = get_imgid_dict(ann)
    img_path = os.path.join(os.getcwd(), "images", folder, img_filename)
    im = io.imread(img_path)
    annids = ann.getAnnIds(imgIds=id_fn_dict[img_filename], iscrowd=None)
    anns = ann.loadAnns(annids)

    # load and display instance annotations
    plt.figure(figsize=(15, 15))
    plt.imshow(im)
    plt.axis('off')
    plt.title(img_filename)
    ann.showAnns(anns)
    plt.show() 
Example 24
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: nstyle.py    License: Apache License 2.0 5 votes vote down vote up
def PreprocessStyleImage(path, shape):
    img = io.imread(path)
    resized_img = transform.resize(img, (shape[2], shape[3]))
    sample = np.asarray(resized_img) * 256
    sample = np.swapaxes(sample, 0, 2)
    sample = np.swapaxes(sample, 1, 2)

    sample[0, :] -= 123.68
    sample[1, :] -= 116.779
    sample[2, :] -= 103.939
    return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2])) 
Example 25
def PreprocessContentImage(path, short_edge, dshape=None):
    img = io.imread(path)
    #logging.info("load the content image, size = %s", img.shape[:2])
    factor = float(short_edge) / min(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
    if dshape is not None:
        # random crop
        xx = int((sample.shape[0] - dshape[2]))
        yy = int((sample.shape[1] - dshape[3]))
        xstart = random.randint(0, xx)
        ystart = random.randint(0, yy)
        xend = xstart + dshape[2]
        yend = ystart + dshape[3]
        sample = sample[xstart:xend, ystart:yend, :]

    # 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", sample.shape)
    return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2])) 
Example 26
def PreprocessStyleImage(path, shape):
    img = io.imread(path)
    resized_img = transform.resize(img, (shape[2], shape[3]))
    sample = np.asarray(resized_img) * 256
    sample = np.swapaxes(sample, 0, 2)
    sample = np.swapaxes(sample, 1, 2)

    sample[0, :] -= 123.68
    sample[1, :] -= 116.779
    sample[2, :] -= 103.939
    return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2])) 
Example 27
Project: view-finding-network   Author: yiling-chen   File: vfn_eval.py    License: GNU General Public License v3.0 5 votes vote down vote up
def evaluate_FCDB():
    slidling_windows_string = open('./sliding_window.json', 'r').read()
    sliding_windows = json.loads(slidling_windows_string)

    cnt = 0
    alpha = 0.75
    alpha_cnt = 0
    accum_boundary_displacement = 0
    accum_overlap_ratio = 0
    crop_cnt = 0

    for item in sliding_windows:
        # print 'processing', item['filename']
        crops = item['crops']
        img_filename = join('FCDB', item['filename'])
        img = io.imread(img_filename)
        height = img.shape[0]
        width = img.shape[1]

        # ground truth
        x = crops[0][0]
        y = crops[0][1]
        w = crops[0][2]
        h = crops[0][3]

        best_x, best_y, best_w, best_h = evaluate_sliding_window(img_filename, crops)
        boundary_displacement = (abs(best_x - x) + abs(best_x + best_w - x - w))/float(width) + (abs(best_y - y) + abs(best_y + best_h - y - h))/float(height)
        accum_boundary_displacement += boundary_displacement
        ratio = overlap_ratio(x, y, w, h, best_x, best_y, best_w, best_h)
        if ratio >= alpha:
            alpha_cnt += 1
        accum_overlap_ratio += ratio
        cnt += 1
        crop_cnt += len(crops)

    print 'Average overlap ratio: {:.4f}'.format(accum_overlap_ratio / cnt)
    print 'Average boundary displacement: {:.4f}'.format(accum_boundary_displacement / (cnt * 4.0))
    print 'Alpha recall: {:.4f}'.format(100 * float(alpha_cnt) / cnt)
    print 'Total image evaluated:', cnt
    print 'Average crops per image:', float(crop_cnt) / cnt 
Example 28
Project: AdaptiveWingLoss   Author: protossw512   File: convert_WFLW.py    License: Apache License 2.0 5 votes vote down vote up
def process_single(single, image_path, image_save_path, landmarks_save_path):
    # print('Processing: {}'.format(single.image_base_name))
    image_full_path = os.path.join(image_path, single.image_base_name)
    image = io.imread(image_full_path)
    if len(image.shape) == 2:
        image = np.stack((image, image, image), -1)

    pts = single.landmarks
    left, top, right, bottom = [int(x) for x in single.bbox]
    lr_pad = int(0.05 * (right - left) / 2)
    tb_pad = int(0.05 * (bottom - top) / 2)
    left = max(0, left - lr_pad)
    right = right + lr_pad
    top = max(0, top - tb_pad)
    bottom = bottom + tb_pad

    center = torch.FloatTensor(
        [right - (right - left) / 2.0, bottom -
            (bottom - top) / 2.0])
    scale_factor = 250.0
    scale = (right - left + bottom - top) / scale_factor
    new_image, new_landmarks = cv_crop(image, pts, center, scale, 450, 0)
    while np.min(new_landmarks) < 10 or np.max(new_landmarks) > 440:
        scale_factor -= 10
        scale = (right - left + bottom - top) / scale_factor
        new_image, new_landmarks = cv_crop(image, pts, center, scale, 450, 0)
        assert (scale_factor > 0), "Landmarks out of boundary!"
    if new_image != []:
        io.imsave(os.path.join(image_save_path, os.path.basename(image_full_path[:-4]+'_' + str(single.idx) + image_full_path[-4:])), new_image)
        np.save(os.path.join(landmarks_save_path, os.path.basename(image_full_path[:-4]+ '_' + str(single.idx) + '.pts')), new_landmarks) 
Example 29
Project: cnn-levelset   Author: wiseodd   File: pascalvoc_util.py    License: MIT License 5 votes vote down vote up
def load_images(self, img_names):
        X = [transform.resize(io.imread(self._img_path(img)), self.img_size)
             for img
             in img_names[self.img_idx]]

        return np.array(X) 
Example 30
Project: cnn-levelset   Author: wiseodd   File: pascalvoc_util.py    License: MIT License 5 votes vote down vote up
def load_segmentation_label_from_imgs(self, img_names):
        def preprocess(img_name):
            img = io.imread(self.segmentation_dir + '/' + img_name + '.png')
            img = transform.resize(img, self.img_size)
            img = color.rgb2grey(img)
            img = (img != 0)
            return img

        y = [preprocess(img) for img in img_names[self.img_idx]]

        return np.array(y)