【问题标题】:How to bin an image tensor so that each pixel value is binned/bucketed into 1 of 10 values in tensorflow如何对图像张量进行分箱,以便将每个像素值分箱/分箱到张量流中 10 个值中的 1 个
【发布时间】:2019-06-29 23:18:14
【问题描述】:

我有一个图片数据集作为张量,每个像素的值介于 0 和 1 之间,并且我有一组“bins”。

bins = [0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95]

我想返回一个张量,每个像素值都是它最近的 bin。例如,如果一个像素是 0.03,它将变成 0.05,如果一个像素是 0.79,它将变成 0.75。

我希望用张量而不是 numpy 来完成。

这是在 numpy 中工作的……张量流在迭代方面似乎是一个完全不同的野兽。我已经尝试过 tf.map_fn 和 tf.scan 进行迭代,但我无法让它工作。

def valueQuant(picture, splitSize):
  #This is the Picture that will be returned
  Quant_Pic = np.zeros((picture.shape[0], picture.shape[1]))

  #go through each pixel of the image
  for y_col in range(picture.shape[0]):  
    for x_row in range(picture.shape[1]):
      #isolate regions based on value
      for i in range(splitSize):
        #low and high values to isolate
        lowFloatRange = float((1/splitSize)*i)
        highFloatRange = float((1/splitSize)*(i+1))
        #value to turn entire clustor
        midRange = lowFloatRange + ((highFloatRange - lowFloatRange)/2)
        #current value of current pixel
        curVal = picture[y_col][x_row]
        #if the current value is within the range of interest
        if(curVal >= lowFloatRange and curVal <= highFloatRange):
            Quant_Pic[y_col][x_row] = midRange

  return Quant_Pic  

我能够仅使用张量流方法找出一个元素明智的方法。

def quant_val(current_input):
    bins = tf.constant([0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95])
    dist = tf.tile(current_input, [10])
    dist = tf.math.subtract(bins, current_input)
    absDist = tf.math.abs(dist)
    idx = tf.math.argmin(absDist)
    output = bins[idx]
    output = tf.expand_dims(output, 0)
    print("output", output)

    return output

current_input = tf.constant([0.53])
quant_val(current_input)

这能够为具有单个值的张量返回正确答案,但我不确定如何将其外推到更大的图像张量结构。任何帮助将非常感激!!!谢谢各位好心人。

【问题讨论】:

    标签: python tensorflow keras deep-learning tensor


    【解决方案1】:

    圆形进场:

    这非常简单易行,但有些 0.5 值向上舍入,有些则向下舍入。如果这不是问题:

    def quant_val(images): #0 to 1
    
        images = (images - 0.05) * 10            #-0.5 to 9.5
        bins = tf.round(images)                  #0 to 9
        bins = tf.clip_by_value(bins, 0, 9)      #possible -1 and 10 due to the remark on top
        return (bins/10) + 0.05                  #0.05 to 0.95
    

    【讨论】:

    • 效果很好。我不敢相信我没有想到。谢谢!
    • Dam 实际上并没有,因为 tensorflow 轮函数不可微分。网络不会训练。我现在正在寻找解决方法。
    • 所以......可能没有简单的方法。我以为那是输入数据(那么就没有问题了)。您确实需要让这些值近似且可微。您可以尝试(不确定数学含义)使用除以 stop_gradients(value) 而不是舍入。
    猜你喜欢
    • 2013-07-30
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多