python+opencv模擬生成運動模糊核


參考:OPENCV2學習(1)_生成運動模糊核(OPENCV2 實現Matlab中fspecial的motion功能)

運動模糊時,模糊后圖片某點的值應該與原圖沿運動角度方向前面的點有關,並且越近鄰影響越大,即權值越大。所以除了確定卷積核之外,還確定了錨點(anchor)

import math
import numpy as np
import cv2
#生成卷積核和錨點
def genaratePsf(length,angle):
    EPS=np.finfo(float).eps                                 
    alpha = (angle-math.floor(angle/ 180) *180) /180* math.pi
    cosalpha = math.cos(alpha)  
    sinalpha = math.sin(alpha)  
    if cosalpha < 0:
        xsign = -1
    elif angle == 90:
        xsign = 0
    else:  
        xsign = 1
    psfwdt = 1;  
    #模糊核大小
    sx = int(math.fabs(length*cosalpha + psfwdt*xsign - length*EPS))  
    sy = int(math.fabs(length*sinalpha + psfwdt - length*EPS))
    psf1=np.zeros((sy,sx))
#psf1是左上角的權值較大,越往右下角權值越小的核。 #這時運動像是從右下角到左上角移動 for i in range(0,sy): for j in range(0,sx): psf1[i][j] = i*math.fabs(cosalpha) - j*sinalpha rad = math.sqrt(i*i + j*j) if rad >= half and math.fabs(psf1[i][j]) <= psfwdt: temp = half - math.fabs((j + psf1[i][j] * sinalpha) / cosalpha) psf1[i][j] = math.sqrt(psf1[i][j] * psf1[i][j] + temp*temp) psf1[i][j] = psfwdt + EPS - math.fabs(psf1[i][j]); if psf1[i][j] < 0: psf1[i][j] = 0 #運動方向是往左上運動,錨點在(0,0) anchor=(0,0) #運動方向是往右上角移動,錨點一個在右上角
#同時,左右翻轉核函數,使得越靠近錨點,權值越大
if angle<90 and angle>0: psf1=np.fliplr(psf1) anchor=(psf1.shape[1]-1,0) elif angle>-90 and angle<0:#同理:往右下角移動 psf1=np.flipud(psf1) psf1=np.fliplr(psf1) anchor=(psf1.shape[1]-1,psf1.shape[0]-1) elif anchor<-90:#同理:往左下角移動 psf1=np.flipud(psf1) anchor=(0,psf1.shape[0]-1) psf1=psf1/psf1.sum() return psf1,anchor

demo:

import motionBlur
kernel,anchor=motionBlur.genaratePsf(20,40)
motion_blur=cv2.filter2D(im,-1,kernel,anchor=anchor)

             after blurred

至於核權值的計算完全使用參考的博文。


免責聲明!

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



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