python利用opencv合成模糊圖像


之前需要評估圖像質量來篩選成像質量不錯的圖片,去除由於對焦,運動等造成的模糊圖像,所以在構建數據集的時候考慮用opencv對清晰的圖片進行處理獲得模糊的圖片從而進行訓練。

1) 運動模糊圖像

一般來說,運動模糊的圖像都是朝同一方向運動的,那么就可以利用cv2.filter2D函數。

import numpy as np

def motion_blur(image, degree=10, angle=20):
    image = np.array(image)
    
    # 這里生成任意角度的運動模糊kernel的矩陣, degree越大,模糊程度越高
    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) 對焦模糊

opencv提供了GaussianBlur函數(具體參見這里).

image = cv2.GaussianBlur(image, ksize=(degree, degree), sigmaX=0, sigmaY=0)

對焦模糊

3) 噪點

其實就是在每個像素點添加隨機擾動:

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

噪點

參考:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM