Python scipy.misc.imsave() Examples

The following are 30 code examples of scipy.misc.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 scipy.misc , or try the search function .
Example #1
Source File: Prepare_TrainData_HR_LR.py    From SRFBN_CVPR19 with MIT License 6 votes vote down vote up
def save_HR_LR(img, size, path, idx):
	HR_img = misc.imresize(img, size, interp='bicubic')
	HR_img = modcrop(HR_img, 4)
	rot180_img = misc.imrotate(HR_img, 180)
	x4_img = misc.imresize(HR_img, 1 / 4, interp='bicubic')
	x4_rot180_img = misc.imresize(rot180_img, 1 / 4, interp='bicubic')

	img_path = path.split('/')[-1].split('.')[0] + '_rot0_' + 'ds' + str(idx) + '.png'
	rot180img_path = path.split('/')[-1].split('.')[0] + '_rot180_' + 'ds' + str(idx) + '.png'
	x4_img_path = path.split('/')[-1].split('.')[0] + '_rot0_' + 'ds' + str(idx) + '.png'
	x4_rot180img_path = path.split('/')[-1].split('.')[0] + '_rot180_' + 'ds' + str(idx) + '.png'

	misc.imsave(save_HR_path + '/' + img_path, HR_img)
	misc.imsave(save_HR_path + '/' + rot180img_path, rot180_img)
	misc.imsave(save_LR_path + '/' + x4_img_path, x4_img)
	misc.imsave(save_LR_path + '/' + x4_rot180img_path, x4_rot180_img) 
Example #2
Source File: predict_video.py    From cat-bbs with MIT License 6 votes vote down vote up
def process_frame(frame_idx, img, model, write_to_dir, conf_threshold, input_size=224):
    """Finds bounding boxes in a video frame, draws these bounding boxes
    and saves the result to HDD.
    """
    # find BBs in frame
    bbs, time_model = find_bbs(img, model, conf_threshold, input_size=input_size)

    # draw BBs
    img_out = np.copy(img)
    for (bb, score) in bbs:
        if score > conf_threshold and bb.width > 2 and bb.height > 2:
            img_out = bb.draw_on_image(img_out, color=[0, 255, 0], thickness=3)

    # save to output directory
    save_to_fp = os.path.join(write_to_dir, "%05d.jpg" % (frame_idx,))
    misc.imsave(save_to_fp, img_out)

    return time_model 
Example #3
Source File: pascal_voc_loader.py    From sunets with MIT License 6 votes vote down vote up
def setup(self, pre_encode=False):

        target_path = self.root + '/combined_annotations/'
        if not os.path.exists(target_path):
            os.makedirs(target_path)

        if pre_encode:
            print("Pre-encoding segmentation masks...")
            for i in tqdm(self.sbd_train_list):
                lbl_path = self.sbd_path + 'dataset/cls/' + i + '.mat'
                lbl = io.loadmat(lbl_path)['GTcls'][0]['Segmentation'][0].astype(np.int32)
                lbl = m.toimage(lbl, high=self.ignore_index, low=0)
                m.imsave(target_path + i + '.png', lbl)
            for i in tqdm(self.sbd_val_list):
                lbl_path = self.sbd_path + 'dataset/cls/' + i + '.mat'
                lbl = io.loadmat(lbl_path)['GTcls'][0]['Segmentation'][0].astype(np.int32)
                lbl = m.toimage(lbl, high=self.ignore_index, low=0)
                m.imsave(target_path + i + '.png', lbl)
            for i in tqdm(self.files['trainval']):
                lbl_path = self.voc_path + 'SegmentationClass/' + i + '.png'
                lbl = self.encode_segmap(m.imread(lbl_path))
                lbl = m.toimage(lbl, high=self.ignore_index, low=0)
                m.imsave(target_path + i + '.png', lbl) 
Example #4
Source File: tracklet_utils_3d_online.py    From TNT with GNU General Public License v3.0 6 votes vote down vote up
def crop_det(det_M, img): 
    global track_struct
    crop_det_folder = track_struct['file_path']['crop_det_folder']
    crop_size = track_struct['track_params']['crop_size']
    if not os.path.isdir(crop_det_folder): 
        os.makedirs(crop_det_folder) 
    
    save_patch_list = []
    for n in range(len(det_M)):
        xmin = int(max(0,det_M[n,1])) 
        xmax = int(min(img.shape[1]-1,det_M[n,1]+det_M[n,3])) 
        ymin = int(max(0,det_M[n,2])) 
        ymax = int(min(img.shape[0]-1,det_M[n,2]+det_M[n,4])) 
        img_patch = img[ymin:ymax,xmin:xmax,:] 
        img_patch = misc.imresize(img_patch, size=[crop_size,crop_size]) 
        patch_name = track_lib.file_name(n,4)+'.png'
        save_path = crop_det_folder+'/'+patch_name 
        misc.imsave(save_path, img_patch)
        save_patch_list.append(save_path)
  
    return save_patch_list 
Example #5
Source File: tracklet_utils_2d_online.py    From TNT with GNU General Public License v3.0 6 votes vote down vote up
def crop_det(det_M, img): 
    global track_struct
    crop_det_folder = track_struct['file_path']['crop_det_folder']
    crop_size = track_struct['track_params']['crop_size']
    if not os.path.isdir(crop_det_folder): 
        os.makedirs(crop_det_folder) 
    
    save_patch_list = []
    for n in range(len(det_M)):
        xmin = int(max(0,det_M[n,1])) 
        xmax = int(min(img.shape[1]-1,det_M[n,1]+det_M[n,3])) 
        ymin = int(max(0,det_M[n,2])) 
        ymax = int(min(img.shape[0]-1,det_M[n,2]+det_M[n,4])) 
        img_patch = img[ymin:ymax,xmin:xmax,:] 
        img_patch = misc.imresize(img_patch, size=[crop_size,crop_size]) 
        patch_name = track_lib.file_name(n,4)+'.png'
        save_path = crop_det_folder+'/'+patch_name 
        misc.imsave(save_path, img_patch)
        save_patch_list.append(save_path)
  
    return save_patch_list 
Example #6
Source File: get_saliency.py    From saliency-2016-cvpr with MIT License 6 votes vote down vote up
def get_saliency_for_shallownet(image_url,sal_url):
    arr_files = glob.glob(image_url+"*.jpg")
    for i in range(len(arr_files)):  
        url_image = arr_files[i]
        image = io.imread(url_image)       
        img = misc.imresize(image,(96,96))
        img = np.asarray(img, dtype = 'float32') / 255.
        img = img.transpose(2,0,1).reshape(3, 96, 96)
        xt = np.zeros((1, 3, 96, 96), dtype='float32')
        xt[0]=img
        y = juntingnet.predict(xt)
        tmp = y.reshape(48,48)
        blured= ndimage.gaussian_filter(tmp, sigma=3)
        sal_map = cv2.resize(tmp,(image.shape[1],image.shape[0]))
        sal_map -= np.min(sal_map)
        sal_map /= np.max(sal_map)
        #saliency = misc.imresize(y,(img.shape[0],img.shape[1]))
        aux = url_image.split("/")[-1].split(".")[0]
        misc.imsave(sal_url+'/'+aux+'.png', sal_map) 
Example #7
Source File: evaluate.py    From iLID with MIT License 6 votes vote down vote up
def kernel_summary(sess):
  with sess.as_default():
    for layer in ["conv1", "conv2", "conv3"]:
      with tf.variable_scope(layer, reuse=True):
        weights = tf.get_variable('weights')
      kernels = tf.unpack(tf.transpose(weights, perm=[3,2,0,1]))
      for i,kernel in enumerate(kernels):
      #[12, 6, 6] -> 12 x [8, 8]
        padding = [[1,1], [1,1]]
        padded_kernels = [tf.pad(single_kernel, padding) for single_kernel in tf.unpack(kernel)]

      #12 x [8, 8] -> [6, 12 * 8]
        horizontally_concatenated = tf.concat(1, padded_kernels)

        image = horizontally_concatenated.eval()

        misc.imsave(layer + "_" + str(i) + ".png", image) 
Example #8
Source File: prepare_kitti.py    From MachineLearning with Apache License 2.0 6 votes vote down vote up
def main():
    for file in os.listdir(data_image_dir):
        if file.endswith(".png"):
            print("Try to copy %s" % file)
            im = misc.imread(os.path.join(data_image_dir, file), mode='RGB')
            height, width, ch = im.shape
            assert ch == IMAGE_DEPTH
            if height == IMAGE_HEIGHT and width == IMAGE_WIDTH and ch == IMAGE_DEPTH:
                misc.imsave(os.path.join(image_dir, file), im)
            else:
                print("Size: (%d, %d, %d) cannot be used." % (height, width, ch))

    for file in os.listdir(data_label_dir):
        if file.endswith(".png"):
            print("Try to converting %s" % file)
            gt_label = convert_to_label_data(os.path.join(data_label_dir, file))
            if gt_label is not None:
                misc.imsave(os.path.join(label_output_dir, file), gt_label) 
Example #9
Source File: helper.py    From DeepWarp with Apache License 2.0 6 votes vote down vote up
def replace_eyes(image, out_eyes, out_shape, out_path, n):
    x_cen, y_cen, half_w, half_h = out_shape
    copy_image = np.copy(image)
    print(image.shape)
    print(out_eyes.shape) # 41,51
    out_eyes = np.squeeze(out_eyes, axis=0)

    # resize and save as eyes only
    # replace = cv2.resize(out_eyes, (51,41)) #(400, 250)
    save_path_and_name = os.path.join(out_path, '{}.jpg'.format(n))
    misc.imsave(save_path_and_name, out_eyes)

    resize_replace = cv2.resize(out_eyes, (2*half_w, 2*half_h)) * 255 # resize to original
    # resize_replace = np.transpose(resize_replace, axes=(1, 0, 2))
    copy_image[(y_cen - half_h):(y_cen + half_h), (x_cen - half_w):(x_cen + half_w), :] = resize_replace.astype(np.uint8)
    image_save_path_and_name = os.path.join(out_path, 'face_{}.jpg'.format(n))
    # print(image_save_path_and_name)
    misc.imsave(image_save_path_and_name, copy_image)
    return None 
Example #10
Source File: helper_functions.py    From Intelligent-Projects-Using-Python with MIT License 6 votes vote down vote up
def data_store(path,action,reward,state):

    if not os.path.exists(path):
        os.makedirs(path)
    else:
        shutil.rmtree(path)
        os.makedirs(path)
    
    df = pd.DataFrame(action, columns=["Steering", "Throttle", "Brake"])
    df["Reward"] = reward
    df.to_csv(path +'car_racing_actions_rewards.csv', index=False)
    
    for i in range(len(state)):
        if rgb_mode == False:
            image = rgb2gray(state[i])
        else:
            image = state[i]

    misc.imsave( path + "img" + str(i) +".png", image) 
Example #11
Source File: utils.py    From GazeCorrection with Apache License 2.0 5 votes vote down vote up
def save_as_gif(images_list, out_path, gif_file_name='all', save_image=False):

    if os.path.exists(out_path) == False:
        os.mkdir(out_path)
    # save as .png
    if save_image == True:
        for n in range(len(images_list)):
            file_name = '{}.png'.format(n)
            save_path_and_name = os.path.join(out_path, file_name)
            misc.imsave(save_path_and_name, images_list[n])
    # save as .gif
    out_path_and_name = os.path.join(out_path, '{}.gif'.format(gif_file_name))
    imageio.mimsave(out_path_and_name, images_list, 'GIF', duration=0.1) 
Example #12
Source File: create_mask_im.py    From PConv_in_tf with Apache License 2.0 5 votes vote down vote up
def save_mask(num_mask, min_units, max_units, new_mask_path, im_file, new_im_path):
    mask_list = []
    for j in range(num_mask):
        mask_init = np.ones([512,512],np.uint8)

        lines = np.random.randint(min_units,max_units,1)[0]
        cicles = np.random.randint(min_units,max_units,1)[0]
        rects = np.random.randint(min_units,max_units,1)[0]
        ovals = np.random.randint(min_units,max_units,1)[0]

        mask_L = draw_line(mask_init,lines)             ##  draw  line
        mask_LR = draw_rect(mask_L,rects,40)            ##  draw  line and rect
        mask_LRO = draw_oval(mask_LR,ovals)        
        mask_list.append(draw_circle(mask_LRO,cicles))
                   ###   save masks
    for j in range(num_mask):
        mask_to_save = np.ones([512,512,3]).astype(np.float32)
        for i in range(3):
            mask_to_save[:,:,i] = mask_to_save[:,:,i] * mask_list[j]
        name = new_mask_path+'mask'+str(j)+'.jpg'
        misc.imsave(name,mask_to_save)
                   ###   save im_with_mask    
    im_dirs = [im_file+i_n for i_n in os.listdir(im_file)]
    for im_dir in im_dirs:
        imraw = misc.imread(im_dir)
        im = misc.imresize(imraw,[512,512])
        for i in range(num_mask):
            im_mask = merge(im,mask_list[i])
            im_mask_name = new_im_path + (im_dir.split('.')[0]).split('/')[-1] +str(i) + '.jpg'       
            misc.imsave(im_mask_name,im_mask)
            
# save_mask(num_mask, min_units, max_units, new_mask_path, im_file, new_im_path)
# save_mask(6, 5, 12, 'D:/nvidainpaint/我写的mask生成程序结果/masks/', 'D:/nvidainpaint/我写的mask生成程序结果/imfiles/', 'D:/nvidainpaint/我写的mask生成程序结果/imfilenew/') 
Example #13
Source File: get_saliency.py    From saliency-2016-cvpr with MIT License 5 votes vote down vote up
def get_saliency_for_deepnet(image_url,sal_url):
    salnet = SalNet(specfile,modelfile)
    arr_files = glob.glob(image_url+"*.jpg")
    for i in range(len(arr_files)):  
        url_image = arr_files[i]
        img = io.imread(url_image)       
        img = np.asarray(img, dtype = 'float32')
        if len(img.shape) == 2:
            img = to_rgb(img)
        sal_map = salnet.get_saliency(img)
        #saliency = misc.imresize(y,(img.shape[0],img.shape[1]))
        aux = url_image.split("/")[-1].split(".")[0]
        misc.imsave(sal_url+'/'+aux+'.png', sal_map) 
Example #14
Source File: utils.py    From FusionGAN-Tensorflow with MIT License 5 votes vote down vote up
def imsave(images, size, path):
    return misc.imsave(path, merge(images, size)) 
Example #15
Source File: train_senet_cpn_onebyone.py    From tf.fashionAI with Apache License 2.0 5 votes vote down vote up
def save_image_with_heatmap(image, height, width, heatmap_size, targets, pred_heatmap, indR, indG, indB):
      if not hasattr(save_image_with_heatmap, "counter"):
          save_image_with_heatmap.counter = 0  # it doesn't exist yet, so initialize it
      save_image_with_heatmap.counter += 1

      img_to_save = np.array(image.tolist()) + 128
      #print(img_to_save.shape)

      img_to_save = img_to_save.astype(np.uint8)

      heatmap0 = np.sum(targets[indR, ...], axis=0).astype(np.uint8)
      heatmap1 = np.sum(targets[indG, ...], axis=0).astype(np.uint8)
      heatmap2 = np.sum(targets[indB, ...], axis=0).astype(np.uint8) if len(indB) > 0 else np.zeros((heatmap_size, heatmap_size), dtype=np.float32)

      img_to_save = imresize(img_to_save, (height, width), interp='lanczos')
      heatmap0 = imresize(heatmap0, (height, width), interp='lanczos')
      heatmap1 = imresize(heatmap1, (height, width), interp='lanczos')
      heatmap2 = imresize(heatmap2, (height, width), interp='lanczos')

      img_to_save = img_to_save/2
      img_to_save[:,:,0] = np.clip((img_to_save[:,:,0] + heatmap0 + heatmap2), 0, 255)
      img_to_save[:,:,1] = np.clip((img_to_save[:,:,1] + heatmap1 + heatmap2), 0, 255)
      #img_to_save[:,:,2] = np.clip((img_to_save[:,:,2]/4. + heatmap2), 0, 255)
      file_name = 'targets_{}.jpg'.format(save_image_with_heatmap.counter)
      imsave(os.path.join(config.DEBUG_DIR, file_name), img_to_save.astype(np.uint8))

      pred_heatmap = np.array(pred_heatmap.tolist())
      #print(pred_heatmap.shape)
      for ind in range(pred_heatmap.shape[0]):
        img = pred_heatmap[ind]
        img = img - img.min()
        img *= 255.0/img.max()
        file_name = 'heatmap_{}_{}.jpg'.format(save_image_with_heatmap.counter, ind)
        imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8))
      return save_image_with_heatmap.counter 
Example #16
Source File: train_hg_subnet.py    From tf.fashionAI with Apache License 2.0 5 votes vote down vote up
def save_image_with_heatmap(image, height, width, heatmap_size, targets, pred_heatmap, indR, indG, indB):
      if not hasattr(save_image_with_heatmap, "counter"):
          save_image_with_heatmap.counter = 0  # it doesn't exist yet, so initialize it
      save_image_with_heatmap.counter += 1

      img_to_save = np.array(image.tolist()) + 120
      #print(img_to_save)

      img_to_save = img_to_save.astype(np.uint8)

      heatmap0 = np.sum(targets[indR, ...], axis=0).astype(np.uint8)
      heatmap1 = np.sum(targets[indG, ...], axis=0).astype(np.uint8)
      heatmap2 = np.sum(targets[indB, ...], axis=0).astype(np.uint8) if len(indB) > 0 else np.zeros((heatmap_size, heatmap_size), dtype=np.float32)

      img_to_save = imresize(img_to_save, (height, width), interp='lanczos')
      heatmap0 = imresize(heatmap0, (height, width), interp='lanczos')
      heatmap1 = imresize(heatmap1, (height, width), interp='lanczos')
      heatmap2 = imresize(heatmap2, (height, width), interp='lanczos')

      img_to_save = img_to_save/2
      img_to_save[:,:,0] = np.clip((img_to_save[:,:,0] + heatmap0 + heatmap2), 0, 255)
      img_to_save[:,:,1] = np.clip((img_to_save[:,:,1] + heatmap1 + heatmap2), 0, 255)
      #img_to_save[:,:,2] = np.clip((img_to_save[:,:,2]/4. + heatmap2), 0, 255)
      file_name = 'targets_{}.jpg'.format(save_image_with_heatmap.counter)
      imsave(os.path.join(config.DEBUG_DIR, file_name), img_to_save.astype(np.uint8))

      pred_heatmap = np.array(pred_heatmap.tolist())
      #print(pred_heatmap.shape)
      for ind in range(pred_heatmap.shape[0]):
        img = pred_heatmap[ind]
        img = img - img.min()
        img *= 255.0/img.max()
        file_name = 'heatmap_{}_{}.jpg'.format(save_image_with_heatmap.counter, ind)
        imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8))
      return save_image_with_heatmap.counter 
Example #17
Source File: train_detxt_cpn_onebyone.py    From tf.fashionAI with Apache License 2.0 5 votes vote down vote up
def save_image_with_heatmap(image, height, width, heatmap_size, targets, pred_heatmap, indR, indG, indB):
      if not hasattr(save_image_with_heatmap, "counter"):
          save_image_with_heatmap.counter = 0  # it doesn't exist yet, so initialize it
      save_image_with_heatmap.counter += 1

      img_to_save = np.array(image.tolist()) + 128
      #print(img_to_save.shape)

      img_to_save = img_to_save.astype(np.uint8)

      heatmap0 = np.sum(targets[indR, ...], axis=0).astype(np.uint8)
      heatmap1 = np.sum(targets[indG, ...], axis=0).astype(np.uint8)
      heatmap2 = np.sum(targets[indB, ...], axis=0).astype(np.uint8) if len(indB) > 0 else np.zeros((heatmap_size, heatmap_size), dtype=np.float32)

      img_to_save = imresize(img_to_save, (height, width), interp='lanczos')
      heatmap0 = imresize(heatmap0, (height, width), interp='lanczos')
      heatmap1 = imresize(heatmap1, (height, width), interp='lanczos')
      heatmap2 = imresize(heatmap2, (height, width), interp='lanczos')

      img_to_save = img_to_save/2
      img_to_save[:,:,0] = np.clip((img_to_save[:,:,0] + heatmap0 + heatmap2), 0, 255)
      img_to_save[:,:,1] = np.clip((img_to_save[:,:,1] + heatmap1 + heatmap2), 0, 255)
      #img_to_save[:,:,2] = np.clip((img_to_save[:,:,2]/4. + heatmap2), 0, 255)
      file_name = 'targets_{}.jpg'.format(save_image_with_heatmap.counter)
      imsave(os.path.join(config.DEBUG_DIR, file_name), img_to_save.astype(np.uint8))

      pred_heatmap = np.array(pred_heatmap.tolist())
      #print(pred_heatmap.shape)
      for ind in range(pred_heatmap.shape[0]):
        img = pred_heatmap[ind]
        img = img - img.min()
        img *= 255.0/img.max()
        file_name = 'heatmap_{}_{}.jpg'.format(save_image_with_heatmap.counter, ind)
        imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8))
      return save_image_with_heatmap.counter 
Example #18
Source File: swa_train_cpn.py    From tf.fashionAI with Apache License 2.0 5 votes vote down vote up
def save_image_with_heatmap(image, height, width, heatmap_size, targets, pred_heatmap, indR, indG, indB):
      if not hasattr(save_image_with_heatmap, "counter"):
          save_image_with_heatmap.counter = 0  # it doesn't exist yet, so initialize it
      save_image_with_heatmap.counter += 1

      img_to_save = np.array(image.tolist()) + 128
      #print(img_to_save.shape)

      img_to_save = img_to_save.astype(np.uint8)

      heatmap0 = np.sum(targets[indR, ...], axis=0).astype(np.uint8)
      heatmap1 = np.sum(targets[indG, ...], axis=0).astype(np.uint8)
      heatmap2 = np.sum(targets[indB, ...], axis=0).astype(np.uint8) if len(indB) > 0 else np.zeros((heatmap_size, heatmap_size), dtype=np.float32)

      img_to_save = imresize(img_to_save, (height, width), interp='lanczos')
      heatmap0 = imresize(heatmap0, (height, width), interp='lanczos')
      heatmap1 = imresize(heatmap1, (height, width), interp='lanczos')
      heatmap2 = imresize(heatmap2, (height, width), interp='lanczos')

      img_to_save = img_to_save/2
      img_to_save[:,:,0] = np.clip((img_to_save[:,:,0] + heatmap0 + heatmap2), 0, 255)
      img_to_save[:,:,1] = np.clip((img_to_save[:,:,1] + heatmap1 + heatmap2), 0, 255)
      #img_to_save[:,:,2] = np.clip((img_to_save[:,:,2]/4. + heatmap2), 0, 255)
      file_name = 'targets_{}.jpg'.format(save_image_with_heatmap.counter)
      imsave(os.path.join(config.DEBUG_DIR, file_name), img_to_save.astype(np.uint8))

      pred_heatmap = np.array(pred_heatmap.tolist())
      #print(pred_heatmap.shape)
      for ind in range(pred_heatmap.shape[0]):
        img = pred_heatmap[ind]
        img = img - img.min()
        img *= 255.0/img.max()
        file_name = 'heatmap_{}_{}.jpg'.format(save_image_with_heatmap.counter, ind)
        imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8))
      return save_image_with_heatmap.counter 
Example #19
Source File: train_hg_onebyone.py    From tf.fashionAI with Apache License 2.0 5 votes vote down vote up
def save_image_with_heatmap(image, height, width, heatmap_size, targets, pred_heatmap, indR, indG, indB):
      if not hasattr(save_image_with_heatmap, "counter"):
          save_image_with_heatmap.counter = 0  # it doesn't exist yet, so initialize it
      save_image_with_heatmap.counter += 1

      img_to_save = np.array(image.tolist()) + 128
      #print(img_to_save.shape)

      img_to_save = img_to_save.astype(np.uint8)

      heatmap0 = np.sum(targets[indR, ...], axis=0).astype(np.uint8)
      heatmap1 = np.sum(targets[indG, ...], axis=0).astype(np.uint8)
      heatmap2 = np.sum(targets[indB, ...], axis=0).astype(np.uint8) if len(indB) > 0 else np.zeros((heatmap_size, heatmap_size), dtype=np.float32)

      img_to_save = imresize(img_to_save, (height, width), interp='lanczos')
      heatmap0 = imresize(heatmap0, (height, width), interp='lanczos')
      heatmap1 = imresize(heatmap1, (height, width), interp='lanczos')
      heatmap2 = imresize(heatmap2, (height, width), interp='lanczos')

      img_to_save = img_to_save/2
      img_to_save[:,:,0] = np.clip((img_to_save[:,:,0] + heatmap0 + heatmap2), 0, 255)
      img_to_save[:,:,1] = np.clip((img_to_save[:,:,1] + heatmap1 + heatmap2), 0, 255)
      #img_to_save[:,:,2] = np.clip((img_to_save[:,:,2]/4. + heatmap2), 0, 255)
      file_name = 'targets_{}.jpg'.format(save_image_with_heatmap.counter)
      imsave(os.path.join(config.DEBUG_DIR, file_name), img_to_save.astype(np.uint8))

      pred_heatmap = np.array(pred_heatmap.tolist())
      #print(pred_heatmap.shape)
      for ind in range(pred_heatmap.shape[0]):
        img = pred_heatmap[ind]
        img = img - img.min()
        img *= 255.0/img.max()
        file_name = 'heatmap_{}_{}.jpg'.format(save_image_with_heatmap.counter, ind)
        imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8))
      return save_image_with_heatmap.counter 
Example #20
Source File: dataset_builder.py    From images-web-crawler with GNU General Public License v3.0 5 votes vote down vote up
def convert_format(cls, source_folder, target_folder,
                       extensions=('.jpg', '.jpeg', '.png'), new_extension='.jpg'):
        """ change images from one format to another (eg. change png files to jpeg) """

        # check source_folder and target_folder:
        cls.check_folder_existance(source_folder, throw_error_if_no_folder=True)
        cls.check_folder_existance(target_folder, display_msg=False)
        if source_folder[-1] == "/":
            source_folder = source_folder[:-1]
        if target_folder[-1] == "/":
            target_folder = target_folder[:-1]

        # read images and reshape:
        print("Change format of '", source_folder, "' files...")
        for filename in os.listdir(source_folder):
            if os.path.isdir(source_folder + '/' + filename):
                cls.convert_format(source_folder + '/' + filename,
                                   target_folder + '/' + filename,
                                   extensions=extensions, new_extension=new_extension)
            else:
                if extensions == '' and os.path.splitext(filename)[1] == '':
                    copy2(source_folder + "/" + filename,
                          target_folder + "/" + filename + new_extension)
                    image = ndimage.imread(target_folder + "/" + filename + new_extension)
                    misc.imsave(target_folder + "/" + filename + new_extension, image)
                else:
                    for extension in extensions:
                        if filename.endswith(extension):
                            new_filename = os.path.splitext(filename)[0] + new_extension
                            copy2(source_folder + "/" + filename,
                                  target_folder + "/" + new_filename)
                            image = ndimage.imread(target_folder + "/" + new_filename)
                            misc.imsave(target_folder + "/" + new_filename, image) 
Example #21
Source File: dataset_builder.py    From images-web-crawler with GNU General Public License v3.0 5 votes vote down vote up
def convert_to_grayscale(cls, source_folder, target_folder,
                             extensions=('.jpg', '.jpeg', '.png')):
        """ convert images from RGB to Grayscale"""

        # check source_folder and target_folder:
        cls.check_folder_existance(source_folder, throw_error_if_no_folder=True)
        cls.check_folder_existance(target_folder, display_msg=False)
        if source_folder[-1] == "/":
            source_folder = source_folder[:-1]
        if target_folder[-1] == "/":
            target_folder = target_folder[:-1]

        # read images and reshape:
        print("Convert '", source_folder, "' images to grayscale...")
        for filename in os.listdir(source_folder):
            if os.path.isdir(source_folder + '/' + filename):
                cls.convert_to_grayscale(source_folder + '/' + filename,
                                         target_folder + '/' + filename,
                                         extensions=extensions)
            else:
                if extensions == '' and os.path.splitext(filename)[1] == '':
                    copy2(source_folder + "/" + filename,
                          target_folder + "/" + filename)
                    image = ndimage.imread(target_folder + "/" + filename, flatten=True)
                    misc.imsave(target_folder + "/" + filename, image)
                else:
                    for extension in extensions:
                        if filename.endswith(extension):
                            copy2(source_folder + "/" + filename,
                                  target_folder + "/" + filename)
                            image = ndimage.imread(target_folder + "/" + filename, flatten=True)
                            misc.imsave(target_folder + "/" + filename, image) 
Example #22
Source File: dataset_builder.py    From images-web-crawler with GNU General Public License v3.0 5 votes vote down vote up
def crop_images(cls, source_folder, target_folder, height=128, width=128,
                       extensions=('.jpg', '.jpeg', '.png')):
        """ copy images and center crop them"""

        # check source_folder and target_folder:
        cls.check_folder_existance(source_folder, throw_error_if_no_folder=True)
        cls.check_folder_existance(target_folder, display_msg=False)
        if source_folder[-1] == "/":
            source_folder = source_folder[:-1]
        if target_folder[-1] == "/":
            target_folder = target_folder[:-1]

        # read images and crop:
        print("Cropping '", source_folder, "' images...")
        for filename in os.listdir(source_folder):
            if os.path.isdir(source_folder + '/' + filename):
                cls.crop_images(source_folder + '/' + filename,
                                   target_folder + '/' + filename,
                                   height, width, extensions=extensions)
            else:
                if extensions == '' and os.path.splitext(filename)[1] == '':
                    copy2(source_folder + "/" + filename,
                          target_folder + "/" + filename)
                    image = ndimage.imread(target_folder + "/" + filename, mode="RGB")
                    [width_original, height_original, _] = image.shape
                    offset_w = (width_original - width) / 2
                    offset_h = (width_original - width) / 2
                    image_cropped = image[offset_w : width + offset_w, offset_h : height + offset_h, :]
                    misc.imsave(target_folder + "/" + filename, image_cropped)
                else:
                    for extension in extensions:
                        if filename.endswith(extension):
                            copy2(source_folder + "/" + filename,
                                  target_folder + "/" + filename)
                            image = ndimage.imread(target_folder + "/" + filename, mode="RGB")
                            [width_original, height_original, _] = image.shape
                            offset_w = (width_original - width) / 2
                            offset_h = (width_original - width) / 2
                            image_cropped = image[offset_w : width + offset_w, offset_h : height + offset_h, :]
                            misc.imsave(target_folder + "/" + filename, image_cropped) 
Example #23
Source File: dataset_builder.py    From images-web-crawler with GNU General Public License v3.0 5 votes vote down vote up
def reshape_images(cls, source_folder, target_folder, height=128, width=128,
                       extensions=('.jpg', '.jpeg', '.png')):
        """ copy images and reshape them"""

        # check source_folder and target_folder:
        cls.check_folder_existance(source_folder, throw_error_if_no_folder=True)
        cls.check_folder_existance(target_folder, display_msg=False)
        if source_folder[-1] == "/":
            source_folder = source_folder[:-1]
        if target_folder[-1] == "/":
            target_folder = target_folder[:-1]

        # read images and reshape:
        print("Resizing '", source_folder, "' images...")
        for filename in os.listdir(source_folder):
            if os.path.isdir(source_folder + '/' + filename):
                cls.reshape_images(source_folder + '/' + filename,
                                   target_folder + '/' + filename,
                                   height, width, extensions=extensions)
            else:
                if extensions == '' and os.path.splitext(filename)[1] == '':
                    copy2(source_folder + "/" + filename,
                          target_folder + "/" + filename)
                    image = ndimage.imread(target_folder + "/" + filename, mode="RGB")
                    image_resized = misc.imresize(image, (height, width))
                    misc.imsave(target_folder + "/" + filename, image_resized)
                else:
                    for extension in extensions:
                        if filename.endswith(extension):
                            copy2(source_folder + "/" + filename,
                                  target_folder + "/" + filename)
                            image = ndimage.imread(target_folder + "/" + filename, mode="RGB")
                            image_resized = misc.imresize(image, (height, width))
                            misc.imsave(target_folder + "/" + filename, image_resized) 
Example #24
Source File: utils.py    From TensorFlow_DCIGN with MIT License 5 votes vote down vote up
def images_to_sprite(arr, path=None):
  assert len(arr) <= 100*100
  arr = arr[...,:3]
  resized = [scipy.misc.imresize(x[..., :3], size=[80, 80]) for x in arr]
  base = np.zeros([8000, 8000, 3], np.uint8)

  for i in range(100):
    for j in range(100):
      index = j+100*i
      if index < len(resized):
        base[80*i:80*i+80, 80*j:80*j+80] = resized[index]
  scipy.misc.imsave(path, base) 
Example #25
Source File: test_pilutil.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_imsave(self):
        picdir = os.path.join(datapath, "data")
        for png in glob.iglob(picdir + "/*.png"):
            with suppress_warnings() as sup:
                # PIL causes a Py3k ResourceWarning
                sup.filter(message="unclosed file")
                sup.filter(DeprecationWarning)
                img = misc.imread(png)
            tmpdir = tempfile.mkdtemp()
            try:
                fn1 = os.path.join(tmpdir, 'test.png')
                fn2 = os.path.join(tmpdir, 'testimg')
                with suppress_warnings() as sup:
                    # PIL causes a Py3k ResourceWarning
                    sup.filter(message="unclosed file")
                    sup.filter(DeprecationWarning)
                    misc.imsave(fn1, img)
                    misc.imsave(fn2, img, 'PNG')

                with suppress_warnings() as sup:
                    # PIL causes a Py3k ResourceWarning
                    sup.filter(message="unclosed file")
                    sup.filter(DeprecationWarning)
                    data1 = misc.imread(fn1)
                    data2 = misc.imread(fn2)
                assert_allclose(data1, img)
                assert_allclose(data2, img)
                assert_equal(data1.shape, img.shape)
                assert_equal(data2.shape, img.shape)
            finally:
                shutil.rmtree(tmpdir) 
Example #26
Source File: utils.py    From Sparsely-Grouped-GAN with MIT License 5 votes vote down vote up
def imsave(images, path):
    images = cv2.cvtColor(images.astype('uint8'), cv2.COLOR_RGB2BGR)
    return cv2.imwrite(path, images) 
Example #27
Source File: dotplots.py    From svviz with MIT License 5 votes vote down vote up
def dotplot2(s1, s2, wordsize=5, overlap=5, verbose=1):
        """ verbose = 0 (no progress), 1 (progress if s1 and s2 are long) or
        2 (progress in any case) """
        doProgress = False
        if verbose > 1 or len(s1)*len(s2) > 1e6:
            doProgress = True

        mat = numpy.ones(((len(s1)-wordsize)/overlap+2, (len(s2)-wordsize)/overlap+2))

        for i in range(0, len(s1)-wordsize, overlap):
            if i % 1000 == 0 and doProgress:
                logging.info("  dotplot progress: {} of {} rows done".format(i, len(s1)-wordsize))
            word1 = s1[i:i+wordsize]

            for j in range(0, len(s2)-wordsize, overlap):
                word2 = s2[j:j+wordsize]

                if word1 == word2 or word1 == word2[::-1]:
                    mat[i/overlap, j/overlap] = 0
        
        imgData = None
        tempDir = tempfile.mkdtemp()
        try:
            path = os.path.join(tempDir, "dotplot.png")
            misc.imsave(path, mat)
            imgData = open(path).read()
        except Exception as e:
            logging.error("Error generating dotplots:'{}'".format(e))
        finally:
            shutil.rmtree(tempDir)
        return imgData 
Example #28
Source File: utils.py    From Sparsely-Grouped-GAN with MIT License 5 votes vote down vote up
def save_images(images, image_path, is_verse=True):
    if is_verse:
        return imsave(inverse_transform(images), path=image_path)
    else:
        return imsave(images, path=image_path) 
Example #29
Source File: utils.py    From Sparsely-Grouped-GAN with MIT License 5 votes vote down vote up
def save_as_gif(images_list, out_path, gif_file_name='all', save_image=False):

    if os.path.exists(out_path) == False:
        os.mkdir(out_path)
    # save as .png
    if save_image == True:
        for n in range(len(images_list)):
            file_name = '{}.png'.format(n)
            save_path_and_name = os.path.join(out_path, file_name)
            misc.imsave(save_path_and_name, images_list[n])
    # save as .gif
    out_path_and_name = os.path.join(out_path, '{}.gif'.format(gif_file_name))
    imageio.mimsave(out_path_and_name, images_list, 'GIF', duration=0.1) 
Example #30
Source File: train_detnet_cpn_onebyone.py    From tf.fashionAI with Apache License 2.0 5 votes vote down vote up
def save_image_with_heatmap(image, height, width, heatmap_size, targets, pred_heatmap, indR, indG, indB):
      if not hasattr(save_image_with_heatmap, "counter"):
          save_image_with_heatmap.counter = 0  # it doesn't exist yet, so initialize it
      save_image_with_heatmap.counter += 1

      img_to_save = np.array(image.tolist()) + 128
      #print(img_to_save.shape)

      img_to_save = img_to_save.astype(np.uint8)

      heatmap0 = np.sum(targets[indR, ...], axis=0).astype(np.uint8)
      heatmap1 = np.sum(targets[indG, ...], axis=0).astype(np.uint8)
      heatmap2 = np.sum(targets[indB, ...], axis=0).astype(np.uint8) if len(indB) > 0 else np.zeros((heatmap_size, heatmap_size), dtype=np.float32)

      img_to_save = imresize(img_to_save, (height, width), interp='lanczos')
      heatmap0 = imresize(heatmap0, (height, width), interp='lanczos')
      heatmap1 = imresize(heatmap1, (height, width), interp='lanczos')
      heatmap2 = imresize(heatmap2, (height, width), interp='lanczos')

      img_to_save = img_to_save/2
      img_to_save[:,:,0] = np.clip((img_to_save[:,:,0] + heatmap0 + heatmap2), 0, 255)
      img_to_save[:,:,1] = np.clip((img_to_save[:,:,1] + heatmap1 + heatmap2), 0, 255)
      #img_to_save[:,:,2] = np.clip((img_to_save[:,:,2]/4. + heatmap2), 0, 255)
      file_name = 'targets_{}.jpg'.format(save_image_with_heatmap.counter)
      imsave(os.path.join(config.DEBUG_DIR, file_name), img_to_save.astype(np.uint8))

      pred_heatmap = np.array(pred_heatmap.tolist())
      #print(pred_heatmap.shape)
      for ind in range(pred_heatmap.shape[0]):
        img = pred_heatmap[ind]
        img = img - img.min()
        img *= 255.0/img.max()
        file_name = 'heatmap_{}_{}.jpg'.format(save_image_with_heatmap.counter, ind)
        imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8))
      return save_image_with_heatmap.counter