## Fuzzy image generation by Python opencv

ShellCollector 2020-11-13 10:01:46
fuzzy image generation python opencv

Remove due to focus , Blurred images caused by motion, etc , So when building data sets, consider using opencv Clear images are processed to obtain fuzzy images for training .

## 1） Motion blur image

Generally speaking , Motion blurred images are moving in the same direction , Then we can use `cv2.filter2D` function .

``````import numpy as np
def motion_blur(image, degree=10, angle=20):
image = np.array(image)
# Here we generate motion blur at any angle kernel Matrix , degree The bigger it is , The more fuzzy
M = cv2.getRotationMatrix2D((degree/2, degree/2), angle, 1)
motion_blur_kernel = np.diag(np.ones(degree))
motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M, (degree, degree))
motion_blur_kernel = motion_blur_kernel / degree
blurred = cv2.filter2D(image, -1, motion_blur_kernel)
# convert to uint8
cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX)
blurred = np.array(blurred, dtype=np.uint8)
return blurred
``````  ## 2) Focus blur

opencv Provides `GaussianBlur` function ( Specific see here ).

``````image = cv2.GaussianBlur(image, ksize=(degree, degree), sigmaX=0, sigmaY=0)
`````` ## 3) noise

In fact, it is to add random perturbation to each pixel ：

``````def gaussian_noise(image, degree=None):
row, col, ch = image.shape
mean = 0
if not degree:
var = np.random.uniform(0.004, 0.01)
else:
var = degree
sigma = var ** 0.5
gauss = np.random.normal(mean, sigma, (row, col, ch))
gauss = gauss.reshape(row, col, ch)
noisy = image + gauss
cv2.normalize(noisy, noisy, 0, 255, norm_type=cv2.NORM_MINMAX)
noisy = np.array(noisy, dtype=np.uint8)
return noisy
`````` 