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


Python io.imsave方法代码示例

本文整理汇总了Python中skimage.io.imsave方法的典型用法代码示例。如果您正苦于以下问题:Python io.imsave方法的具体用法?Python io.imsave怎么用?Python io.imsave使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在skimage.io的用法示例。


在下文中一共展示了io.imsave方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: predict_dataset

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def predict_dataset(self, dataset, export_path):
        """
        Predicts the images in the given dataset and saves it to disk.

        Args:
            dataset: the dataset of images to be exported, instance of unet.dataset.Image2D
            export_path: path to folder where results to be saved
        """
        self.net.train(False)
        chk_mkdir(export_path)

        for batch_idx, (X_batch, *rest) in enumerate(DataLoader(dataset, batch_size=1)):
            if isinstance(rest[0][0], str):
                image_filename = rest[0][0]
            else:
                image_filename = '%s.png' % str(batch_idx + 1).zfill(3)

            X_batch = Variable(X_batch.to(device=self.device))
            y_out = self.net(X_batch).cpu().data.numpy()

            io.imsave(os.path.join(export_path, image_filename), y_out[0, 1, :, :]) 
开发者ID:cosmic-cortex,项目名称:pytorch-UNet,代码行数:23,代码来源:model.py

示例2: _prepare_images

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def _prepare_images(path_out, im_size=IMAGE_SIZE):
    """ generate and prepare synth. images for registration

    :param str path_out: path to the folder
    :param tuple(int,int) im_size: desired image size
    :return tuple(str,str): paths to target and source image
    """
    image = resize(data.astronaut(), output_shape=im_size, mode='constant')
    img_target = random_noise(image, var=IMAGE_NOISE)
    path_img_target = os.path.join(path_out, NAME_IMAGE_TARGET)
    io.imsave(path_img_target, img_target)

    # warp synthetic image
    tform = AffineTransform(scale=(0.9, 0.9),
                            rotation=0.2,
                            translation=(200, -50))
    img_source = warp(image, tform.inverse, output_shape=im_size)
    img_source = random_noise(img_source, var=IMAGE_NOISE)
    path_img_source = os.path.join(path_out, NAME_IMAGE_SOURCE)
    io.imsave(path_img_source, img_source)
    return path_img_target, path_img_source 
开发者ID:Borda,项目名称:BIRL,代码行数:23,代码来源:bm_comp_perform.py

示例3: convertToGrayScale

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def convertToGrayScale (rootDir, dirNames):
    nbConverted = 0
    for root, dirs, files in os.walk(rootDir):
        files.sort(key=tryint)
        for file in files:
            parentDir = os.path.basename(root)
            fname = os.path.splitext(file)[0]  # no path, no extension. only filename
            if parentDir in dirNames:
                # convert all images in here to grayscale, store to dirName_gray
                newDirPath = ''.join([os.path.dirname(root), os.sep, parentDir + "_gray"])
                newFilePath = ''.join([newDirPath, os.sep, fname + "_gray.jpg"])
                if not os.path.exists(newDirPath):
                    os.makedirs(newDirPath)
                if not os.path.exists(newFilePath):
                    # read in grayscale, write to new path
                    # with OpenCV: weird results (gray image larger than color ?!?)
                    # img = cv2.imread(root+os.sep+file, 0)
                    # cv2.imwrite(newFilePath, img)
                    
                    img_gray = rgb2gray(io.imread(root + os.sep + file))
                    io.imsave(newFilePath, img_gray)  # don't write to disk if already exists
                    nbConverted += 1
    
    # print(nbConverted, " files have been converted to Grayscale")
    return 0 
开发者ID:matthijsvk,项目名称:TCDTIMITprocessing,代码行数:27,代码来源:helpFunctions.py

示例4: colorize

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def colorize():
    path = './img/colorize/colorize2.png'
    # cv2.imwrite('./img/colorize3.png', cv2.imread(path, 0))
    x, y, image_shape = get_train_data(path)
    model = build_model()
    model.load_weights('./data/simple_colorize.h5')
    output = model.predict(x)
    output *= 128
    tmp = np.zeros((200, 200, 3))
    tmp[:, :, 0] = x[0][:, :, 0]
    tmp[:, :, 1:] = output[0]
    colorizePath = path.replace(".png", "-res.png")
    imsave(colorizePath, lab2rgb(tmp))
    cv2.imshow("I", cv2.imread(path))
    cv2.imshow("II", cv2.imread(colorizePath))
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # imsave("test_image_gray.png", rgb2gray(lab2rgb(tmp))) 
开发者ID:vipstone,项目名称:faceai,代码行数:21,代码来源:colorize.py

示例5: save_img

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def save_img(file_name, img):
    from skimage import io

    if isinstance(img, Variable):
        img = img.data.cpu().numpy()

    if len(img.shape) == 4:
        img = img.squeeze(0)

    # scipy expects shape (W, H, 3)
    if img.shape[0] == 3:
        img = img.transpose(2, 1, 0)

    img = img.clip(0, 255)
    img = img.astype(np.uint8)

    io.imsave(file_name, img) 
开发者ID:maximecb,项目名称:gym-miniworld,代码行数:19,代码来源:utils.py

示例6: generate_copy

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def generate_copy(images, boxes, out):
    global num_adfree
    if num_adfree < MAX_NUM_ADFREE:
        num_adfree += len(images)
    else:
        logger.info("Created enough ADFREE")
        return
    if boxes:
        logger.error("%s has boxes that should be replaced ... skipped", out)
        return
    logger.info("Copying %s", out)
    tmp_out = '{}-copy'.format(out)
    annotation_path = os.path.join(ANNOTATION_PATH, tmp_out + '.txt')
    image_path = os.path.join(IMAGES_PATH, tmp_out + '.png')
    with open(annotation_path, 'w+') as f:
        f.write('')
    try:
        io.imsave(image_path, images[0])
        logger.info("Saved %s", tmp_out)
    except ValueError:
        logger.error("Failed to save %s", image_path) 
开发者ID:ftramer,项目名称:ad-versarial,代码行数:23,代码来源:generator.py

示例7: rotate_images

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def rotate_images(file_path, degrees_of_rotation, lst_imgs):
    '''
    Rotates image based on a specified amount of degrees

    INPUT
        file_path: file path to the folder containing images.
        degrees_of_rotation: Integer, specifying degrees to rotate the
        image. Set number from 1 to 360.
        lst_imgs: list of image strings.

    OUTPUT
        Images rotated by the degrees of rotation specififed.
    '''

    for l in lst_imgs:
        img = io.imread(file_path + str(l) + '.jpeg')
        img = rotate(img, degrees_of_rotation)
        io.imsave(file_path + str(l) + '_' + str(degrees_of_rotation) + '.jpeg', img) 
开发者ID:llSourcell,项目名称:AI_in_Medicine_Clinical_Imaging_Classification,代码行数:20,代码来源:rotate_images.py

示例8: SaveImage

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def SaveImage(img, filename, remove_noise=0.):
    logging.info('save output to %s', filename)
    out = PostprocessImage(img)
    if remove_noise != 0.0:
        out = denoise_tv_chambolle(out, weight=remove_noise, multichannel=True)
    io.imsave(filename, out) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:8,代码来源:nstyle.py

示例9: SaveImage

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def SaveImage(img, filename, remove_noise=0.02):
    logging.info('save output to %s', filename)
    out = PostprocessImage(img)
    if remove_noise != 0.0:
        out = denoise_tv_chambolle(out, weight=remove_noise, multichannel=True)
    io.imsave(filename, out) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:8,代码来源:data_processing.py

示例10: main

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def main():
    global mainDir, fontsChinese
    pygame.init()
    shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
    os.makedirs(OUTPUT_DIR)
    labels = open(os.path.join(OUTPUT_DIR, "labels.txt"), 'w')
    labels.truncate()
    i = 0
    chiIdx = 0
    outDir = None

    # http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing
    selfPath = os.path.abspath(inspect.getfile(inspect.currentframe()))
    mainDir, _ = os.path.split(selfPath)
    dirFonts = os.path.join(mainDir, 'fonts_Chinese')
    fnFonts = filter(lambda fn: os.path.splitext(fn)[1].lower() in [
                     '.ttf', '.otf'], os.listdir(dirFonts))
    fontsChinese = list(
        map(lambda fn: os.path.join(dirFonts, fn), fnFonts))

    chiFiles = sorted(glob.glob('newsgroup/corpus-*.txt'))
    outputPerChiFile = OUTPUT_NUM / len(chiFiles)
    initChineseSource(chiFiles[0])
    chiIdx += 1

    for im, text in generate(OUTPUT_NUM):
        if i % OUTPUT_BATCH == 0:
            outDir = os.path.join(OUTPUT_DIR, str(int(i/OUTPUT_BATCH)))
            os.makedirs(outDir)
        if i != 0 and i % outputPerChiFile == 0:
            initChineseSource(chiFiles[chiIdx])
            chiIdx += 1
        outf = os.path.join(outDir, '%s.jpg' % i)
        # pygame.image.save(im, outf) #pygame
        # im.save(outf) #PIL image
        io.imsave(outf, im)  # scikit-image
        labels.write('%s/%s.jpg\t%s\n' % (int(i/OUTPUT_BATCH),
                                          i, text))
        print('done %s.jpg, text: %s' % (i, text))
        i += 1
    labels.close() 
开发者ID:deepinsight,项目名称:insightocr,代码行数:43,代码来源:gen.py

示例11: process_single

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
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) 
开发者ID:protossw512,项目名称:AdaptiveWingLoss,代码行数:32,代码来源:convert_WFLW.py

示例12: save_image_collections

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def save_image_collections(x, filename, shape=(10, 10), scale_each=False,
                           transpose=False):
    """
    :param shape: tuple
        The shape of final big images.
    :param x: numpy array
        Input image collections. (number_of_images, rows, columns, channels) or
        (number_of_images, channels, rows, columns)
    :param scale_each: bool
        If true, rescale intensity for each image.
    :param transpose: bool
        If true, transpose x to (number_of_images, rows, columns, channels),
        i.e., put channels behind.
    :return: `uint8` numpy array
        The output image.
    """
    from skimage import io, img_as_ubyte
    from skimage.exposure import rescale_intensity
    makedirs(filename)
    n = x.shape[0]
    if transpose:
        x = x.transpose(0, 2, 3, 1)
    if scale_each is True:
        for i in range(n):
            x[i] = rescale_intensity(x[i], out_range=(0, 1))
    n_channels = x.shape[3]
    x = img_as_ubyte(x)
    r, c = shape
    if r * c < n:
        print('Shape too small to contain all images')
    h, w = x.shape[1:3]
    ret = np.zeros((h * r, w * c, n_channels), dtype='uint8')
    for i in range(r):
        for j in range(c):
            if i * c + j < n:
                ret[i * h:(i + 1) * h, j * w:(j + 1) * w, :] = x[i * c + j]
    ret = ret.squeeze()
    io.imsave(filename, ret) 
开发者ID:thu-ml,项目名称:zhusuan,代码行数:40,代码来源:utils.py

示例13: handle_single

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def handle_single(self, path):
        try:
            img = skimage_io.imread(path, flatten=True)
            img = self.data_proc.apply(img)

            if not self.dry_run:
                skimage_io.imsave(path, img)
        except ValueError as e:
            print(e)
            print(path) 
开发者ID:Calamari-OCR,项目名称:calamari,代码行数:12,代码来源:apply_data_preprocessing.py

示例14: saveSpectrogramToImage

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def saveSpectrogramToImage(spectrogram, filePath):
    image = np.clip((spectrogram - np.min(spectrogram)) / (np.max(spectrogram) - np.min(spectrogram)), 0, 1)
    # Ignore Low-contrast image warnings
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        io.imsave(filePath, image) 
开发者ID:Veleslavia,项目名称:vimss,代码行数:8,代码来源:Input.py

示例15: save_image

# 需要导入模块: from skimage import io [as 别名]
# 或者: from skimage.io import imsave [as 别名]
def save_image(image, save_dir, name):
    """
    Save image by unprocessing and converting to rgb.
    :param image: iamge to save
    :param save_dir: location to save image at
    :param name: prefix to save filename
    :return:
    """
    image = color.lab2rgb(image)
    io.imsave(os.path.join(save_dir, name + ".png"), image) 
开发者ID:shekkizh,项目名称:Colorization.tensorflow,代码行数:12,代码来源:TensorflowUtils.py


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