如何减少张量流图像计算的内存使用

2024-04-29 01:05:53 发布

您现在位置:Python中文网/ 问答频道 /正文

目的

我现在用的是张量流。 我想做一些图像计算:

  1. 将图像分成12*12个正方形
  2. 对于每个子正方形,将其拆分为6*(2*12)水平和;6(12*2)个垂直矩形
  3. 对于每个矩形,计算其水平像素;垂直梯度的平均值和标准差

所以,对于每一个子平方,我想要48个值,也就是

6*(hori_gx_mean,hori_gy_mean,hori_gx_std,hori_gy_std)----24   
and    
6*(vert_gx_mean,vert_gy_mean,vert_gx_std,vert_gy_std)----24

问题

现在我有一个1920x1280图像,有3个频道。 而且每行图像的内存成本约为0.5g,而且价格不菲。 我想减少内存使用

TensorFlow安装位置(源或二进制):binary
TensorFlow版本(使用下面的命令):1.14.0 Python版本:3.7.3 x64 CUDA/cuDNN版本:cuda_10.0.130_411.31_win10 & cudnn-10.0-windows10-x64-v7.5.1.10

  1. 通过tf.image.decode_image读取图像 为了得到图像的宽度和高度,我运行Session来生成形状值
tf.Session().run(tf.image.decode_image(tf.read_file(imgDir)))/255.0
  1. 计算平均值和标准差
def FeaExt(srcImg):
    _retExp = []
    feaBuf = []
    # srcImg.shape is (w,h,deep)
    _src = tf.dtypes.cast(srcImg, tf.float16)
    # tf.image.image_gradients need a [batch_size, h, w, d] shape 
    _src = tf.reshape(_src, [1] + list(_src.shape))

    for y in range(int(srcImg.shape[0]/12)-1):
        for x in range(int(srcImg.shape[1]/12)-1):
            sub12_12 = tf.image.crop_to_bounding_box(_src, y*12, x*12, 12, 12)
            # computes every 2*12 and 12*2 subSet in sub12_12
            for div in range(6):
                # height=2 width=12
                sub12_2 = tf.image.crop_to_bounding_box(
                    sub12_12, div * 2, 0, 2, 12)
                # height=12 width=2
                sub2_12 = tf.image.crop_to_bounding_box(
                    sub12_12, 0, div* 2, 12, 2)

                # computes gradient, return (dy, dx)
                _dy_12_2, _dx_12_2 = tf.image.image_gradients(
                    tf.image.rgb_to_grayscale(sub12_2))
                _dy_2_12, _dx_2_12 = tf.image.image_gradients(sub2_12)

                # computes standard deviation
                _stDy12_2 = tf.math.reduce_std(_dy_12_2)
                _stDx12_2 = tf.math.reduce_std(_dx_12_2)

                _stDy2_12 = tf.math.reduce_std(_dy_2_12)
                _stDx2_12 = tf.math.reduce_std(_dx_2_12)
                # compute gradient's mean
                _uDy12_2 = tf.math.reduce_mean(_dy_12_2)
                _uDx12_2 = tf.math.reduce_mean(_dx_12_2)

                _uDy2_12 = tf.math.reduce_mean(_dy_2_12)
                _uDx2_12 = tf.math.reduce_mean(_dx_2_12)

                # 6 set of horizontal and vertical sub-rectangle feature
                feaBuf.append([_uDy12_2, _uDx12_2, _stDy12_2, _stDx12_2,
                                _uDy2_12, _uDx2_12, _stDy2_12, _stDx2_12])
            _retExp.append(feaBuf)
            feaBuf=[]

    return _retExp

理论上,有(1920/12)*48*8(float64)字节的数据,
但每行图像大约需要0.5gb内存。
我想减少内存使用


Tags: 图像imagesrcreducetfmathmeanstd