Python skimage.io() Examples

The following are 30 code examples of skimage.io(). 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 also want to check out all available functions/classes of the module skimage , or try the search function .
Example #1
Source File: classify_demo.py    From 12306-captcha with Apache License 2.0 6 votes vote down vote up
def train_main():
    path_dir = '/home/ruifengshan/github/12306-captcha/data/download/'
    img_names = filter(lambda s: not s.startswith("."), os.listdir(path_dir + '/all'))

    for img_name in img_names:
        im = cut_image.read_image(os.path.join(path_dir + '/all', img_name))
        if im is None:
            print "该图片{ %s }处理异常: " % img_name
            continue
        # 转为灰度图
        list_text = judge_words(cut_image.get_text(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)))
        print "文字部分的内容:"
        for text in list_text:
            print text
        judge_image(cut_image.get_image(im), list_text)
        skimage.io.imshow(im) 
Example #2
Source File: image_processing.py    From text-to-image with MIT License 6 votes vote down vote up
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') 
Example #3
Source File: image_processing.py    From text-to-image with MIT License 6 votes vote down vote up
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') 
Example #4
Source File: save_result.py    From DenseMatchingBenchmark with MIT License 6 votes vote down vote up
def __call__(self, result, out_dir, image_name):
        result_tool = ShowResultTool()
        result = result_tool(result, color_map='gray', bins=100)

        if 'GrayDisparity' in result.keys():
            grayEstDisp = result['GrayDisparity']
            gray_save_path = osp.join(out_dir, 'disp_0')
            mkdir_or_exist(gray_save_path)
            skimage.io.imsave(osp.join(gray_save_path, image_name), (grayEstDisp * 256).astype('uint16'))

        if 'ColorDisparity' in result.keys():
            colorEstDisp = result['ColorDisparity']
            color_save_path = osp.join(out_dir, 'color_disp')
            mkdir_or_exist(color_save_path)
            plt.imsave(osp.join(color_save_path, image_name), colorEstDisp, cmap=plt.cm.hot)

        if 'GroupColor' in result.keys():
            group_save_path = os.path.join(out_dir, 'group_disp')
            mkdir_or_exist(group_save_path)
            plt.imsave(osp.join(group_save_path, image_name), result['GroupColor'], cmap=plt.cm.hot)

        if 'ColorConfidence' in result.keys():
            conf_save_path = os.path.join(out_dir, 'confidence')
            mkdir_or_exist(conf_save_path)
            plt.imsave(osp.join(conf_save_path, image_name), result['ColorConfidence']) 
Example #5
Source File: save_result.py    From DenseMatchingBenchmark with MIT License 6 votes vote down vote up
def __call__(self, result, out_dir, image_name):
        result_tool = ShowResultTool()
        result = result_tool(result)
        if 'GrayDisparity' in result.keys():
            grayEstDisp = result['GrayDisparity']
            gray_save_path = osp.join(out_dir, 'flow_0')
            mkdir_or_exist(gray_save_path)
            skimage.io.imsave(osp.join(gray_save_path, image_name), (grayEstDisp * 256).astype('uint16'))

        if 'ColorDisparity' in result.keys():
            colorEstDisp = result['ColorDisparity']
            color_save_path = osp.join(out_dir, 'color_disp')
            mkdir_or_exist(color_save_path)
            plt.imsave(osp.join(color_save_path, image_name), colorEstDisp, cmap=plt.cm.hot)

        if 'GroupColor' in result.keys():
            group_save_path = os.path.join(out_dir, 'group_flow')
            mkdir_or_exist(group_save_path)
            plt.imsave(osp.join(group_save_path, image_name), result['GroupColor'], cmap=plt.cm.hot) 
Example #6
Source File: helpers.py    From Feed-Forward-Style-Transfer with MIT License 6 votes vote down vote up
def load_img(path):
    """Returns a numpy array of an image specified by its path.
    
    Args:
        path: string representing the file path of the image to load
        
    Returns:
        resized_img: numpy array representing the loaded RGB image
        shape: the image shape
    """

    # 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 
Example #7
Source File: image_processing.py    From TAC-GAN with GNU General Public License v3.0 6 votes vote down vote up
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') 
Example #8
Source File: qc.py    From spinalcordtoolbox with MIT License 6 votes vote down vote up
def _update_html_assets(self, json_data):
        """Update the html file and assets"""
        assets_path = os.path.join(os.path.dirname(__file__), 'assets')
        dest_path = self.qc_params.root_folder

        with io.open(os.path.join(assets_path, 'index.html')) as template_index:
            template = Template(template_index.read())
            output = template.substitute(sct_json_data=json.dumps(json_data))
            io.open(os.path.join(dest_path, 'index.html'), 'w').write(output)

        for path in ['css', 'js', 'imgs', 'fonts']:
            src_path = os.path.join(assets_path, '_assets', path)
            dest_full_path = os.path.join(dest_path, '_assets', path)
            if not os.path.exists(dest_full_path):
                os.makedirs(dest_full_path, exist_ok = True)
            for file_ in os.listdir(src_path):
                if not os.path.isfile(os.path.join(dest_full_path, file_)):
                    sct.copy(os.path.join(src_path, file_),
                             dest_full_path) 
Example #9
Source File: visualClef.py    From Deep-Plant with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def crop_image(self, x, target_height=224, target_width=224):
        image = skimage.img_as_float(skimage.io.imread(x)).astype(np.float32)

        if len(image.shape) == 2:
            image = np.tile(image[:,:,None], 3)
        elif len(image.shape) == 4:
            image = image[:,:,:,0]
    
        height, width, rgb = image.shape
        if width == height:
            resized_image = cv2.resize(image, (target_height,target_width))
      
        elif height < width:
            resized_image = cv2.resize(image, (int(width * float(target_height)/height), target_width))
            cropping_length = int((resized_image.shape[1] - target_height) / 2)
            resized_image = resized_image[:,cropping_length:resized_image.shape[1] - cropping_length]

        else:
            resized_image = cv2.resize(image, (target_height, int(height * float(target_width) / width)))
            cropping_length = int((resized_image.shape[0] - target_width) / 2)
            resized_image = resized_image[cropping_length:resized_image.shape[0] - cropping_length,:]

        return cv2.resize(resized_image, (target_height, target_width))    
    
####### Network Parameters ######## 
Example #10
Source File: dataSampling.py    From adascan-public with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #11
Source File: art.py    From neural-art with MIT License 6 votes vote down vote up
def create_transformer(self):
        """
        Create the preprocessor and deprocessor using the default settings for
        the VGG-19 network.
        """
        # Give transformer necessary imput shape. Should be specified from
        # argparse arguments when creating the net
        transformer = caffe.io.Transformer(
            {'data': self.net.blobs['data'].data.shape}
        )
        # Order of the channels in the input data (not sure why necessary)
        transformer.set_transpose('data', (2, 0, 1))
        # Use BGR rather than RGB
        transformer.set_channel_swap('data', (2, 1, 0))
        # Subtract mean pixel
        transformer.set_mean('data', MEAN_PIXEL)
        # Use 8bit image values
        transformer.set_raw_scale('data', 255)

        return transformer 
Example #12
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def load_scaled_image( filename, color=True ):
    """
    Load an image converting from grayscale or alpha as needed.
    From KChen

    Args:
        filename : string
        color : boolean
            flag for color format. True (default) loads as RGB while False
            loads as intensity (if image is already grayscale).
    Returns
        image : an image with type np.float32 in range [0, 1]
            of size (H x W x 3) in RGB or
            of size (H x W x 1) in grayscale.
    By kchen 
    """
    img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32)
    if img.ndim == 2:
        img = img[:, :, np.newaxis]
        if color:
            img = np.tile(img, (1, 1, 3))
    elif img.shape[2] == 4:
        img = img[:, :, :3]
    return img 
Example #13
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def load_scaled_image( filename, color=True ):
    """
    Load an image converting from grayscale or alpha as needed.
    From KChen

    Args:
        filename : string
        color : boolean
            flag for color format. True (default) loads as RGB while False
            loads as intensity (if image is already grayscale).
    Returns
        image : an image with type np.float32 in range [0, 1]
            of size (H x W x 3) in RGB or
            of size (H x W x 1) in grayscale.
    By kchen 
    """
    img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32)
    if img.ndim == 2:
        img = img[:, :, np.newaxis]
        if color:
            img = np.tile(img, (1, 1, 3))
    elif img.shape[2] == 4:
        img = img[:, :, :3]
    return img 
Example #14
Source File: art.py    From neural-art with MIT License 6 votes vote down vote up
def set_content_target(self, img):
        """
        Create content representation of image and set as the content target.
        """
        # XXX: Assume only one content layer
        cl = CONTENT_LAYERS[0]
        contenti = caffe.io.load_image(img)
        # Resize image, set net and transformer shapes accordingly
        scaled = self.resize_image(contenti)
        self.resize_caffes(scaled)

        contenti_pp = self.transformer.preprocess('data', scaled)
        self.net.blobs['data'].data[...] = contenti_pp
        self.net.forward()

        self.content_target = self.net.blobs[cl].data[0].copy()
        # Get contenti_pp (after transformer)
        self.content_target = (
            np.reshape(
                self.content_target,
                (self.content_target.shape[0],
                 self.content_target.shape[1] * self.content_target.shape[2]))
        ) 
Example #15
Source File: utils.py    From Texture-Synthesis with MIT License 6 votes vote down vote up
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) 
Example #16
Source File: image.py    From deepdish with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load(path, dtype=np.float64):
    """
    Loads an image from file.

    Parameters
    ----------
    path : str
        Path to image file.
    dtype : np.dtype
        Defaults to ``np.float64``, which means the image will be returned as a
        float with values between 0 and 1. If ``np.uint8`` is specified, the
        values will be between 0 and 255 and no conversion cost will be
        incurred.
    """
    _import_skimage()
    import skimage.io
    im = skimage.io.imread(path)
    if dtype == np.uint8:
        return im
    elif dtype in {np.float16, np.float32, np.float64}:
        return im.astype(dtype) / 255
    else:
        raise ValueError('Unsupported dtype') 
Example #17
Source File: utils.py    From Texture-Synthesis with MIT License 6 votes vote down vote up
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 
Example #18
Source File: dataloader.py    From pytorch-retinanet with Apache License 2.0 5 votes vote down vote up
def load_image(self, image_index):
        img = skimage.io.imread(self.image_names[image_index])

        if len(img.shape) == 2:
            img = skimage.color.gray2rgb(img)

        return img.astype(np.float32)/255.0 
Example #19
Source File: image.py    From hdrnet with Apache License 2.0 5 votes vote down vote up
def imread(path):
  return skimage.io.imread(path) 
Example #20
Source File: trainLoaderN.py    From DeepLiDAR with MIT License 5 votes vote down vote up
def input_loader(path):
    img = skimage.io.imread(path)
    imgG = skimage.color.rgb2gray(img)
    img = img.astype(np.float32)
    normals = img * 1.0 / 127.5 - np.ones_like(img) * 1.0

    mask = np.zeros_like(img).astype(np.float32)
    mask[:, :, 0] = np.where(imgG > 0, 1.0, 0.0)
    mask[:, :, 1] = np.where(imgG > 0, 1.0, 0.0)
    mask[:, :, 2] = np.where(imgG > 0, 1.0, 0.0)

    return normals,mask 
Example #21
Source File: trainLoader.py    From DeepLiDAR with MIT License 5 votes vote down vote up
def sparse_loader(lidar2_path):
    img2 = skimage.io.imread(lidar2_path)
    img2 = img2 * 1.0 / 256.0
    mask2 = np.where(img2 > 0.0, 1.0, 0.0)
    lidar2 = np.reshape(img2, [img2.shape[0], img2.shape[1], 1]).astype(np.float32)
    return lidar2,mask2 
Example #22
Source File: trainLoader.py    From DeepLiDAR with MIT License 5 votes vote down vote up
def input_loader(path):
    img = skimage.io.imread(path)
    depth = img *1.0 / 256.0
    depth = np.reshape(depth, [img.shape[0], img.shape[1], 1]).astype(np.float32)
    return depth 
Example #23
Source File: trainLoader.py    From DeepLiDAR with MIT License 5 votes vote down vote up
def default_loader(path):
    img = skimage.io.imread(path)
    return img 
Example #24
Source File: image_loader.py    From CVTron with Apache License 2.0 5 votes vote down vote up
def load_image(path, height, width):
    img = skimage.io.imread(path)
    img = img / 255.0
    assert (0 <= img).all() and (img <= 1.0).all()
    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]
    resized_img = skimage.transform.resize(crop_img, (height, width))
    return resized_img 
Example #25
Source File: load_ops.py    From taskonomy with MIT License 5 votes vote down vote up
def segment_pixel_sample_semantic( template, new_dims, num_pixels, domain, mask=None, is_aws=False ):
    '''
    Segmentation

    Returns:
    --------
        pixels: size num_pixels x 3 numpy array
    '''
    if template.split('/')[-1].isdigit(): 
        template = template.split('/')
        if template[0] == '':
            template[0] = os.sep
        template[-1] = "point_{point_id}_view_{view_id}_domain_{{domain}}.png".format(
                    point_id=template[-2], view_id=template[-1])
        template[-2] = '{domain}'
        template = os.path.join(*template)
    filename = template.format( domain=domain )
    
    #img = load_raw_image( filename, color=False, is_aws=is_aws )
    img = skimage.io.imread( filename )
    img = scipy.misc.imresize(img, tuple(new_dims), interp='nearest') 
    #img = resize_image( img, new_dims )

    valid_pixels = list(zip(*np.where(np.squeeze(img) != 0))) 
    pixs = random.sample(valid_pixels, num_pixels)

    pix_segment = [list(i) + [int(img[i[0]][i[1]])] for i in pixs]
    pix_segment = np.array(pix_segment)
    return pix_segment 
Example #26
Source File: load_ops.py    From taskonomy with MIT License 5 votes vote down vote up
def segment_pixel_sample_semantic_rebalanced( template, new_dims, num_pixels, domain, mask=None, is_aws=False, root='/home/ubuntu/task-taxonomy-331b' ):
    '''
    Segmentation

    Returns:
    --------
        pixels: size num_pixels x 3 numpy array
    '''
    if template.split('/')[-1].isdigit(): 
        template = template.split('/')
        if template[0] == '':
            template[0] = os.sep
        template[-1] = "point_{point_id}_view_{view_id}_domain_{{domain}}.png".format(
                    point_id=template[-2], view_id=template[-1])
        template[-2] = '{domain}'
        template = os.path.join(*template)
    filename = template.format( domain=domain )
    
    #img = load_raw_image( filename, color=False, is_aws=is_aws )
    img = skimage.io.imread( filename )
    img = scipy.misc.imresize(img, tuple(new_dims), interp='nearest') 
    #img = resize_image( img, new_dims )

    valid_pixels = list(zip(*np.where(np.squeeze(img) != 0))) 
    pixs = random.sample(valid_pixels, num_pixels)
    img[img == 0] == 1
    img = img - 1
    prior_factor = np.load(os.path.join(root,'lib', 'data', 'semseg_prior_factor.npy'))
    
    #pix_segment = [list(i) + [int(img[i[0]][i[1]])] + [prior_factor[int(img[i[0]][i[1]])]/7. ] for i in pixs]
    pix_segment = [list(i) + [int(img[i[0]][i[1]])] + [1. ] for i in pixs]
    pix_segment = np.array(pix_segment)
    return pix_segment 
Example #27
Source File: load_ops.py    From taskonomy with MIT License 5 votes vote down vote up
def semantic_segment( template, new_dims, domain ):
    '''
    Segmentation

    Returns:
    --------
        pixels: size num_pixels x 3 numpy array
    '''
    if template.split('/')[-1].isdigit(): 
        template = template.split('/')
        if template[0] == '':
            template[0] = os.sep
        template[-1] = "point_{point_id}_view_{view_id}_domain_{{domain}}.png".format(
                    point_id=template[-2], view_id=template[-1])
        template[-2] = '{domain}'
        template = os.path.join(*template)
    filename = template.format( domain=domain )
    if not os.path.isfile(filename):
        return np.zeros(tuple(new_dims)), np.zeros(tuple(new_dims))
    if os.stat(filename).st_size < 100:
        return np.zeros(tuple(new_dims)), np.zeros(tuple(new_dims))
    img = skimage.io.imread( filename )
    img = scipy.misc.imresize(img, tuple(new_dims), interp='nearest') 
    mask = img > 0.1
    mask = mask.astype(float)
    img[img == 0] = 1
    img = img - 1
    return img, mask 
Example #28
Source File: load_ops.py    From taskonomy with MIT License 5 votes vote down vote up
def semantic_segment_rebalanced_linear_inverse( template, new_dims, domain, root='/home/ubuntu/task-taxonomy-331b' ):
    '''
    Segmentation

    Returns:
    --------
        pixels: size num_pixels x 3 numpy array
    '''
    if template.split('/')[-1].isdigit(): 
        template = template.split('/')
        if template[0] == '':
            template[0] = os.sep
        template[-1] = "point_{point_id}_view_{view_id}_domain_{{domain}}.png".format(
                    point_id=template[-2], view_id=template[-1])
        template[-2] = '{domain}'
        template = os.path.join(*template)
    filename = template.format( domain=domain )
    if not os.path.isfile(filename):
        return np.zeros(tuple(new_dims)), np.zeros(tuple(new_dims))
    if os.stat(filename).st_size < 100:
        return np.zeros(tuple(new_dims)), np.zeros(tuple(new_dims))
    img = skimage.io.imread( filename )
    img = scipy.misc.imresize(img, tuple(new_dims), interp='nearest') 
    mask = img > 0.1
    mask = mask.astype(float)
    img[img == 0] = 1
    img = img - 1
    prior_factor = np.load(os.path.join(root,'lib', 'data', 'semseg_avg_inv.npy'))
    rebalance = prior_factor[img]
    mask = mask * rebalance
    return img, mask 
Example #29
Source File: load_ops.py    From taskonomy with MIT License 5 votes vote down vote up
def semantic_segment_rebalanced( template, new_dims, domain, root='/home/ubuntu/task-taxonomy-331b' ):
    '''
    Segmentation

    Returns:
    --------
        pixels: size num_pixels x 3 numpy array
    '''
    if template.split('/')[-1].isdigit(): 
        template = template.split('/')
        if template[0] == '':
            template[0] = os.sep
        template[-1] = "point_{point_id}_view_{view_id}_domain_{{domain}}.png".format(
                    point_id=template[-2], view_id=template[-1])
        template[-2] = '{domain}'
        template = os.path.join(*template)
    filename = template.format( domain=domain )
    if not os.path.isfile(filename):
        return np.zeros(tuple(new_dims)), np.zeros(tuple(new_dims))
    if os.stat(filename).st_size < 100:
        return np.zeros(tuple(new_dims)), np.zeros(tuple(new_dims))
    img = skimage.io.imread( filename )
    img = scipy.misc.imresize(img, tuple(new_dims), interp='nearest') 
    mask = img > 0.1
    mask = mask.astype(float)
    img[img == 0] = 1
    img = img - 1
    prior_factor = np.load(os.path.join(root,'lib', 'data', 'semseg_prior_factor.npy'))
    rebalance = prior_factor[img]
    mask = mask * rebalance
    return img, mask 
Example #30
Source File: vgg19.py    From InsightFace_TF with MIT License 5 votes vote down vote up
def load_image(path):
    # load image
    img = skimage.io.imread(path)
    img = img / 255.0
    if ((0 <= img).all() and (img <= 1.0).all()) is False:
        raise Exception("image value should be [0, 1]")
    # 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