数据增强


随机添加光点

class halo():
    """
    u:高斯分布的均值
    sigma:方差
    nums:在一张图片中随机添加几个光点
    prob:使用halo的概率
    """
    def __init__(self,nums,u=0,sigma=0.2,prob=0.5):
        self.u=u#均值
        self.sig=math.sqrt(sigma)#标准差
        self.nums=nums
        self.prob=prob
    def create_kernel(self,maxh=32,maxw=50):
        height_scope=[10,maxh]#高度范围
        weight_scope=[20,maxw]#宽度范围
        x=np.linspace(self.u-3*self.sig,self.u+3*self.sig,random.randint(*height_scope))
        y=np.linspace(self.u-3*self.sig,self.u+3*self.sig,random.randint(*weight_scope))
        Gauss_map=np.zeros((len(x),len(y)))
        for i in range(len(x)):
            for j in range(len(y)):
                Gauss_map[i,j]=np.exp(-((x[i]-self.u)**2+(y[j]-self.u)**2)/(2*self.sig**2))/(
                    math.sqrt(2*math.pi)*self.sig)
        return Gauss_map
    def __call__(self, img):
        if random.random()img_h:
                    endx=img_h
                    Gauss_map=Gauss_map[1:img_h-pointx+1,:]
                if endy>img_w:
                    endy=img_w
                    Gauss_map=Gauss_map[:,1:img_w-pointy+1]

                #加上不均匀光照
                img1[pointx:endx,pointy:endy]+=Gauss_map*255.0
            img1[img1>255.0]=255.0#进行限幅,不然uint8会从0开始重新计数
            img=img1
               #将array转换为image
        return Image.fromarray(np.uint8(img))
    net=halo(100,0,0.2,0.5)
    pil_im=Image.open('D:/zwy.jpg').convert('L')
    img=net(pil_im)
    img.show()

随机增强图像亮度

class RandomBrightness(object):
    """
    随机改变亮度
    pil:pil格式的图片
    """
    def __init__(self,prob=1.5):
        self.prob=prob
    def __call__(self, pil):
        rgb=np.asarray(pil)
        if random.random()
    net=RandomBrightness()
    img=cv2.imread("D:/hjb.jpg")
    img=net(img)
    cv2.imshow("rgb",img)
    cv2.waitKey(0)
    cv2.destroyWindow()

相关