随机添加光点
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()<self.prob:
#初始化一个高斯核,32为高度方向的最大值,60为宽度方向的最大值
Gauss_map=self.create_kernel(32,60)
###################################
#PIL image转换为array
img1=np.asarray(img)
#修改图片的读取格式
#img1.flags.writeable=True #将数组改写为读写模式
###################################
nums=random.randint(1,self.nums) #随机生成[1,nums]个光点
img1=img1.astype(np.float)#将img1变换成float类型
for i in range(nums):
#处理这nums个随机点
img_h,img_w=img1.shape
#在原图中随机找一个点
pointx=random.randint(0,img_h-10)
pointy=random.randint(0,img_w-10)
#判断是否超出限制
h,w=Gauss_map.shape
endx=pointx+h
endy=pointy+w
if endx>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()<self.prob:
hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
h,s,v=cv2.split(hsv)
adjust=random.choice([0.5,0.7,0.9,1.2,1.5,1.7])
v=v*adjust
#将v修改到[0,255]区间内
v=np.clip(v,0,255).astype(hsv.dtype)
hsv=cv2.merge((h,s,v))
rgb=cv2.cvtColor(hsv,cv2.COLOR_HSV2RGB)
return rgb
net=RandomBrightness()
img=cv2.imread("D:/hjb.jpg")
img=net(img)
cv2.imshow("rgb",img)
cv2.waitKey(0)
cv2.destroyWindow()