从 Tensorflow 中的图像张量中提取随机非重叠补丁

Extract random non-overlapping patches from image tensor in Tensorflow

我想用 Tensorflow 提取 3 个随机的、不重叠的 80 x 80 子图像。我该怎么做?下图应该给出了一个想法。

我想我找到了解决方案,如果您有任何建议,请继续。

  @tf.function
  def sample_img(img,frame_dim=(80,80),seed=42,n=3,padding='VALID'):
   if n > (img.shape[0] * img.shape[1]) // (frame_dim[0] * frame_dim[1]):
     padding = 'SAME' 

   patches = tf.image.extract_patches(tf.reshape(img,shape=(-1,*img.shape)),
                         [1,*frame_dim,1],
                         [1,*frame_dim,1],
                         [1,1,1,1],padding=padding)

   patches_res = tf.reshape(patches,shape=(-1,*frame_dim,img.shape[2]))

   ixs = tf.reshape(tf.range(patches_res.shape[0],dtype=tf.int64),shape=(1,-1))
   ixs_sampled = tf.random.uniform_candidate_sampler(ixs,
                                                  patches_res.shape[0],n,
                                           unique=True,range_max=patches_res.shape[0])

   ixs_sampled_res = tf.reshape(ixs_sampled.sampled_candidates,shape=(n,1))