人体检测常用的数据增强方法之——随机亮度


Table of Contents

效果:

代码实现

函数分析

原图和hsv图:

np.where(condition, x, y)


效果:

参考CSP网络的Github源码,人体检测常用的两个数据增强方法:水平随机翻转,随机亮度

水平翻转code很多,下面只讲一下随机明暗亮度,实际中亮度范围根据实际需要选择,比如0.7-1.3

由原始变为最亮:(范围0.5-1.9),正常亮度为1

亮度为1.9
左边原图,右边亮度1.9

由原始变为最暗:

代码实现

随机亮度:(这对于网络的明暗适应性很重要)

import cv2
from matplotlib import pyplot as plt
import numpy as np
def _brightness(image, min=0.5, max=2.0):
    '''
    Randomly change the brightness of the input image.

    Protected against overflow.
    '''
    hsv = cv2.cvtColor(image,cv2.COLOR_RGB2HSV)

    random_br = np.random.uniform(min,max)
    #random_br=1.9
    #To protect against overflow: Calculate a mask for all pixels
    #where adjustment of the brightness would exceed the maximum
    #brightness value and set the value to the maximum at those pixels.
    mask = hsv[:,:,2] * random_br > 255
    v_channel = np.where(mask, 255, hsv[:,:,2] * random_br)
    hsv[:,:,2] = v_channel

    return cv2.cvtColor(hsv,cv2.COLOR_HSV2RGB)

def random_bright():
    img_path='./fruits.jpg'
    img = cv2.imread(img_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.figure()
    plt.subplot(1,2,1)
    plt.imshow(img)
    # plt.show()


    brightness = (0.5, 2, 0.5)
    img = _brightness(img, min=brightness[0], max=brightness[1])
    cv2.imwrite('./docs/img.jpg',img)
    plt.subplot(1, 2, 2)
    plt.imshow(img)
    plt.show()



if __name__=="__main__":
    random_bright()

函数分析

单独测试:(simple test)

原图和hsv图:

 

其中的np.where用法:

np.where(condition, x, y)

满足条件(condition),输出x,不满足输出y。