Python skimage.io.imsave() Examples

The following are 30 code examples of skimage.io.imsave(). 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.io , or try the search function .
Example #1
Source File: utils.py    From gym-miniworld with Apache License 2.0 6 votes vote down vote up
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) 
Example #2
Source File: rotate_images.py    From AI_in_Medicine_Clinical_Imaging_Classification with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: colorize.py    From faceai with MIT License 6 votes vote down vote up
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))) 
Example #4
Source File: helpFunctions.py    From TCDTIMITprocessing with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: generator.py    From ad-versarial with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: rotate_images.py    From eyenet with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: bm_comp_perform.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #8
Source File: model.py    From pytorch-UNet with MIT License 6 votes vote down vote up
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, :, :]) 
Example #9
Source File: data.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def saveResult(save_path,npyfile,flag_multi_class = False,num_class = 2):
    for i,item in enumerate(npyfile):
        img = labelVisualize(num_class,COLOR_DICT,item) if flag_multi_class else item[:,:,0]
        io.imsave(os.path.join(save_path,"%d_predict.png"%i),img) 
Example #10
Source File: data_io.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_img_2_nifti_gray(path_img, path_out):
    """ converting standard image to Nifti format

    :param str path_img: path to input image
    :param str path_out: path to output directory
    :return str: path to output image

    >>> np.random.seed(0)
    >>> img = np.random.random((150, 125))
    >>> p_in = './temp_sample-image.png'
    >>> io.imsave(p_in, img)
    >>> p_out = convert_img_2_nifti_gray(p_in, '.')
    >>> p_out
    'temp_sample-image.nii'
    >>> os.remove(p_out)
    >>> os.remove(p_in)
    """
    assert os.path.exists(path_img), 'missing input: %s' % path_img
    assert os.path.exists(path_out), 'missing output: %s' % path_out
    name_img_out = os.path.splitext(os.path.basename(path_img))[0] + '.nii'
    path_img_out = os.path.join(os.path.dirname(path_out), name_img_out)
    logging.debug('Convert image to Nifti format "%s" ->  "%s"',
                  path_img, path_img_out)

    img = io_imread(path_img)
    img = color.rgb2gray(img)

    img = np.swapaxes(img, 1, 0)
    nim = nibabel.Nifti1Pair(img, np.eye(4))
    nibabel.save(nim, path_img_out)

    # for k in nim.header.keys():
    #     print('{:20s}: \t{}'.format(k, nim.header[k]))
    return path_img_out 
Example #11
Source File: data.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def saveResult(save_path,npyfile,flag_multi_class = False,num_class = 2):
    for i,item in enumerate(npyfile):
        img = labelVisualize(num_class,COLOR_DICT,item) if flag_multi_class else item[:,:,0]
        io.imsave(os.path.join(save_path,"%d_predict.png"%i),img) 
Example #12
Source File: data_io.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def io_imsave(path_img, img):
    """ just a wrapper to suppers debug messages from the PIL function

    :param str path_img:
    :param ndarray img: image
    """
    io.imsave(path_img, img) 
Example #13
Source File: data.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def saveResult(save_path,npyfile,flag_multi_class = False,num_class = 2):
    for i,item in enumerate(npyfile):
        img = labelVisualize(num_class,COLOR_DICT,item) if flag_multi_class else item[:,:,0]
        io.imsave(os.path.join(save_path,"%d_predict.png"%i),img) 
Example #14
Source File: demo_retinanet.py    From Grad-CAM.pytorch with Apache License 2.0 5 votes vote down vote up
def save_image(image_dicts, input_image_name, layer_name, network='retinanet', output_dir='./results'):
    prefix = os.path.splitext(input_image_name)[0]
    for key, image in image_dicts.items():
        if key == 'predict_box':
            io.imsave(os.path.join(output_dir,
                                   '{}-{}-{}.jpg'.format(prefix, network, key)),
                      image)
        else:
            io.imsave(os.path.join(output_dir,
                                   '{}-{}-{}-{}.jpg'.format(prefix, network, layer_name, key)),
                      image) 
Example #15
Source File: data.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def saveResult(save_path,npyfile,flag_multi_class = False,num_class = 2):
    for i,item in enumerate(npyfile):
        img = labelVisualize(num_class,COLOR_DICT,item) if flag_multi_class else item[:,:,0]
        io.imsave(os.path.join(save_path,"%d_predict.png"%i),img) 
Example #16
Source File: data.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def saveResult(save_path,npyfile,flag_multi_class = False,num_class = 2):
    for i,item in enumerate(npyfile):
        img = labelVisualize(num_class,COLOR_DICT,item) if flag_multi_class else item[:,:,0]
        io.imsave(os.path.join(save_path,"%d_predict.png"%i),img) 
Example #17
Source File: data.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def saveResult(save_path,npyfile,flag_multi_class = False,num_class = 2):
    for i,item in enumerate(npyfile):
        img = labelVisualize(num_class,COLOR_DICT,item) if flag_multi_class else item[:,:,0]
        io.imsave(os.path.join(save_path,"%d_predict.png"%i),img) 
Example #18
Source File: brain_pipeline.py    From brain_segmentation with MIT License 5 votes vote down vote up
def save_labels(fns):
    '''
    INPUT list 'fns': filepaths to all labels
    '''
    progress.currval = 0
    for label_idx in progress(xrange(len(labels))):
        slices = io.imread(labels[label_idx], plugin = 'simpleitk')
        for slice_idx in xrange(len(slices)):
            io.imsave('Labels/{}_{}L.png'.format(label_idx, slice_idx), slices[slice_idx]) 
Example #19
Source File: demo.py    From Grad-CAM.pytorch with Apache License 2.0 5 votes vote down vote up
def save_image(image_dicts, input_image_name, network='frcnn', output_dir='./results'):
    prefix = os.path.splitext(input_image_name)[0]
    for key, image in image_dicts.items():
        io.imsave(os.path.join(output_dir, '{}-{}-{}.jpg'.format(prefix, network, key)), image) 
Example #20
Source File: main.py    From Grad-CAM.pytorch with Apache License 2.0 5 votes vote down vote up
def save_image(image_dicts, input_image_name, network, output_dir):
    prefix = os.path.splitext(input_image_name)[0]
    for key, image in image_dicts.items():
        io.imsave(os.path.join(output_dir, '{}-{}-{}.jpg'.format(prefix, network, key)), image) 
Example #21
Source File: get_mean_image.py    From taskonomy with MIT License 5 votes vote down vote up
def save_data(statistic, cfg, args):
    # Save the statistic data
    print("Computing statistic")
    start = time.time()
    statistic_image = np.squeeze(statistic.get()).astype(
        get_dtype(get_bit_depth(cfg)))
    # print(statistic_image)
    print("dtype: {}".format(statistic_image.dtype))
    print("shape: {}".format(statistic_image.shape))
    print("min/max: {}/{}".format(statistic_image.min(), statistic_image.max()))
    print("Computed statistic ({:.2f} secs)".format(time.time() - start))

    print("Writing pkl")
    with open(os.path.join(cfg['log_dir'], "{}_label.pkl").format(args.stat_type), 'wb') as f:
        pkl.dump(statistic_image, f)
   
    print("Writing png to {}".format(
        os.path.join(cfg['log_dir'], "{}_label.png").format(args.stat_type)))
    if len(statistic_image.shape) == 0:
        statistic_image = statistic_image[np.newaxis, np.newaxis]
        saved_val = np.squeeze(statistic.saved_val)[np.newaxis, np.newaxis]
    elif len(statistic_image.shape) == 1:
        print(statistic_image.shape)
        statistic_image = statistic_image[:, np.newaxis]
        try:
            saved_val = np.squeeze(statistic.saved_val)[:, np.newaxis]
        except: # it's an index for a 1-hot encoding
            saved_val = np.zeros_like(statistic_image)
            saved_val[int(statistic.saved_val)] = 1.
    else:
        saved_val = np.squeeze(statistic.saved_val)

    if len(statistic_image.shape) == 2 or statistic_image.shape[-1] in [1,3,4]:
        io.imsave( os.path.join(cfg['log_dir'], "{}_label.png").format(args.stat_type), statistic_image )
        try:
            io.imsave( os.path.join(cfg['log_dir'], "single_label.png"), saved_val.astype(
                get_dtype(get_bit_depth(cfg))) )
        except:
            tb.print_exc()

    print("Done :)") 
Example #22
Source File: RAG_threshold.py    From Pic-Numero with MIT License 5 votes vote down vote up
def block_process(img):
    func = lambda block: io.imsave("Block/{}.png".format(Helper.generate_random_id()), block)#Display.save_image("Block/{}.png".format(Helper.generate_random_id()), block)
    Helper.block_proc(img, (50,1900), func) 
Example #23
Source File: RAG_threshold.py    From Pic-Numero with MIT License 5 votes vote down vote up
def extract_roi(img, labels_to_keep=[1,2]):
    label_img = segmentation.slic(img, compactness=30, n_segments=6)
    labels = np.unique(label_img);print(labels)
    gray = rgb2gray(img);

    for label in labels:
        if(label not in labels_to_keep):
            logicalIndex = (label_img == label)
            gray[logicalIndex] = 0;

    Display.show_image(gray)
    io.imsave("grayy.png", gray) 
Example #24
Source File: gui.py    From Pic-Numero with MIT License 5 votes vote down vote up
def didClickSubmitButton(self, event):
        print(self.imageFilePath)
        img = img_as_ubyte(io.imread(CLUSTER_IMAGE_FILENAME))
        roi_img = spectral_roi.extract_roi(img, gui_checkbox_handlers.getSelectedClusters())
        roi_img_filename = "{}.png".format(Helper.generate_random_id())
        io.imsave(roi_img_filename, roi_img)
        Display.show_image(roi_img, roi_img_filename) 
Example #25
Source File: PicNumero.py    From Pic-Numero with MIT License 5 votes vote down vote up
def blockfunc(block):
    global img_data

    # Check if not all zeros
    if(numpy.any(block)):
        #io.imsave("Block2/{}.png".format(Helper.generate_random_id()), block)
        img_data.append(block)


################### COUNTING BY REGRESSION ##################################### 
Example #26
Source File: basic.py    From VAE-Tensorflow with MIT License 5 votes vote down vote up
def imwrite(image, path):
    """Save an [-1.0, 1.0] image."""
    iio.imsave(path, im2float(image)) 
Example #27
Source File: gen_pic.py    From uai-sdk with Apache License 2.0 5 votes vote down vote up
def generate(size,char,char_index,save_path,font_path,times):
    #kernel = np.ones((3,3),np.uint8) #kernel of erode or dilate 
    char=str(char)
    l_char=len(char)
    
    #char=unicode(char,'utf-8')
    #l_char=len(char)
    width=l_char*size
    img = Image.new('RGB',(width,size+20),'white')
    draw = ImageDraw.Draw(img)
    #char=unicode(char,'utf-8')
    #maxsize=min(width/l_char/height,0.8)
    #minsize=maxsize-0.1
    
    #sizeofchar=np.arange(minsize,maxsize+0.05,0.05)
    #print(round(width/l_char/height,2),maxsize,minsize)
    #sizeofchar=[0.4,0.45]
    #size= sizeofchar[random.randint(0,len(sizeofchar)-1)]
    
    font = ImageFont.truetype(font_path,size)
    draw.text((0,0),char,(0,0,0),font=font)   
    IMG_SAVEPATH = os.path.join(save_path,str(char_index))
    if (not os.path.exists(IMG_SAVEPATH)):
        os.makedirs(IMG_SAVEPATH)        
    rotate = random.randint(-2, 2)
    img = img.rotate(rotate)
    img_0 = np.array(img)
    noise_modes=['gaussian','poisson','salt','pepper']
    noise_mode=noise_modes[random.randint(0,len(noise_modes)-1)]
    img_1 = skimage.util.random_noise(img_0, mode=noise_mode,seed=None, clip=True)
    #img_2 = cv2.erode(img_0,kernel,iterations = 1)  
    #img_3 = cv2.dilate(img_0,kernel,iterations = 1) 
    #img_3 = skimage.util.random_noise(img_2, mode=noise_mode,seed=None, clip=True)
    #img_5 = skimage.util.random_noise(img_3, mode=noise_mode,seed=None, clip=True)
    for index in range(2):
        io.imsave(os.path.join(IMG_SAVEPATH,str(times)+'_'+str(index)+'.jpg'),eval('img_'+str(index))) 
Example #28
Source File: jhamski.py    From facial_expressions with Apache License 2.0 5 votes vote down vote up
def save_image(img, name, trans_type):
    name = os.path.splitext(name)[0]
    script_dir = os.path.dirname(__file__)

    full_path_images = os.path.join(script_dir, '../images/', name + "_" + trans_type + '.png')
    io.imsave(full_path_images, img)
    #io.imsave(name + "_" + trans_type + '.png', img,)


#setup image transformation functions 
Example #29
Source File: locate_tissue.py    From LiverCancerSeg with MIT License 5 votes vote down vote up
def locate_tissue(slides_dir):
    slide_list = []
    svs_file_list = filesystem.find_ext_files(slides_dir, "svs")
    slide_list.extend(svs_file_list)
    SVS_file_list = filesystem.find_ext_files(slides_dir, "SVS")
    slide_list.extend(SVS_file_list)

    tissue_dir = os.path.join(os.path.dirname(slides_dir), "Visualization/TissueLoc")
    filesystem.overwrite_dir(tissue_dir)
    for ind, slide_path in enumerate(slide_list):
        print("processing {}/{}".format(ind+1, len(slide_list)))
        # locate tissue contours with default parameters
        cnts, d_factor = tl.locate_tissue_cnts(slide_path, max_img_size=2048, smooth_sigma=13,
                                               thresh_val=0.88, min_tissue_size=120000)
        cnts = sorted(cnts, key=lambda x: cv2.contourArea(x), reverse=True)

        # if len(cnts) != 1:
        #     print("There are {} contours in {}".format(len(cnts), os.path.basename(slide_path)))

        # load slide
        select_level, select_factor = tl.select_slide_level(slide_path, max_size=2048)
        wsi_head = pyramid.load_wsi_head(slide_path)
        slide_img = wsi_head.read_region((0, 0), select_level, wsi_head.level_dimensions[select_level])
        slide_img = np.asarray(slide_img)[:,:,:3]
        slide_img = np.ascontiguousarray(slide_img, dtype=np.uint8)

        # change not valid poly to convex_hull
        cnt_arr = cv_cnt_to_np_arr(cnts[0])
        cnt_poly = np_arr_to_poly(cnt_arr)
        if cnt_poly.is_valid == True:
            valid_cnt = cnts[0].astype(int)
        else:
            valid_arr = poly_to_np_arr(cnt_poly.convex_hull)
            valid_cnt = np_arr_to_cv_cnt(valid_arr).astype(int)
        cv2.drawContours(slide_img, [valid_cnt], 0, (0, 255, 0), 8)

        # overlay and save
        # cv2.drawContours(slide_img, cnts, 0, (0, 255, 0), 8)
        tissue_save_name = os.path.splitext(os.path.basename(slide_path))[0] + ".png"
        tissue_save_path = os.path.join(tissue_dir, tissue_save_name)
        io.imsave(tissue_save_path, slide_img) 
Example #30
Source File: helper_dataset.py    From reseg with GNU General Public License v3.0 5 votes vote down vote up
def save_image(outpath, img):
    import errno
    try:
        os.makedirs(os.path.dirname(outpath))
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise e
        pass
    imsave(outpath, img)