加上雨点噪声
import cv2
import numpy as np
def get_noise ( img, value= 10 ) :
'''
#生成噪声图像
>>> 输入: img图像
value= 大小控制雨滴的多少
>>> 返回图像大小的模糊噪声图像
'''
noise = np. random. uniform( 0 , 256 , img. shape[ 0 : 2 ] )
v = value * 0.01
noise[ np. where( noise < ( 256 - v) ) ] = 0
k = np. array( [ [ 0 , 0.1 , 0 ] ,
[ 0.1 , 8 , 0.1 ] ,
[ 0 , 0.1 , 0 ] ] )
noise = cv2. filter2D( noise, - 1 , k)
'''cv2.imshow('img',noise)
cv2.waitKey()
cv2.destroyWindow('img')'''
return noise
def rain_blur ( noise, length= 10 , angle= 0 , w= 1 ) :
'''
将噪声加上运动模糊,模仿雨滴
>>>输入
noise:输入噪声图,shape = img.shape[0:2]
length: 对角矩阵大小,表示雨滴的长度
angle: 倾斜的角度,逆时针为正
w: 雨滴大小
>>>输出带模糊的噪声
'''
trans = cv2. getRotationMatrix2D( ( length/ 2 , length/ 2 ) , angle- 45 , 1 - length/ 100.0 )
dig = np. diag( np. ones( length) )
k = cv2. warpAffine( dig, trans, ( length, length) )
k = cv2. GaussianBlur( k, ( w, w) , 0 )
blurred = cv2. filter2D( noise, - 1 , k)
cv2. normalize( blurred, blurred, 0 , 255 , cv2. NORM_MINMAX)
blurred = np. array( blurred, dtype= np. uint8)
return blurred
def alpha_rain ( rain, img, beta = 0.8 ) :
rain = np. expand_dims( rain, 2 )
rain_effect = np. concatenate( ( img, rain) , axis= 2 )
rain_result = img. copy( )
rain = np. array( rain, dtype= np. float32)
rain_result[ : , : , 0 ] = rain_result[ : , : , 0 ] * ( 255 - rain[ : , : , 0 ] ) / 255.0 + beta* rain[ : , : , 0 ]
rain_result[ : , : , 1 ] = rain_result[ : , : , 1 ] * ( 255 - rain[ : , : , 0 ] ) / 255 + beta* rain[ : , : , 0 ]
rain_result[ : , : , 2 ] = rain_result[ : , : , 2 ] * ( 255 - rain[ : , : , 0 ] ) / 255 + beta* rain[ : , : , 0 ]
cv2. imwrite( 'rain_result.png' , np. uint8( rain_result) )
img = cv2. imread( 'cv.png' )
noise = get_noise( img, value= 500 )
rain = rain_blur( noise, length= 50 , angle= - 30 , w= 3 )
alpha_rain( rain, img, beta= 0.6 )