Hướng dẫn convolve image with gaussian kernel python - chuyển đổi hình ảnh với trăn hạt nhân gaussian

Ghi chú

Nhấn vào đây để tải xuống mã ví dụ đầy đủhere to download the full example code

Làm mờ một hình ảnh (../../../../data/elephant.png) bằng cách sử dụng hạt nhân Gaussian.

Construction rất dễ thực hiện với FFT: kết hợp hai tín hiệu sôi lên để nhân FFT của chúng (và thực hiện FFT nghịch đảo).

import numpy as np
from scipy import fftpack
import matplotlib.pyplot as plt

Ảnh gốc¶

Hướng dẫn convolve image with gaussian kernel python - chuyển đổi hình ảnh với trăn hạt nhân gaussian

Chuẩn bị một hạt nhân chập Gaussian

Thực hiện tích chập qua FFT¶

# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)

Hướng dẫn convolve image with gaussian kernel python - chuyển đổi hình ảnh với trăn hạt nhân gaussian

Bài tập tiếp theo (chỉ khi bạn quen thuộc với công cụ này):

Một đường viền được bọc của người Viking xuất hiện ở các cạnh trên bên trái và trên cùng của hình ảnh. Điều này là do phần đệm không được thực hiện chính xác và không tính đến kích thước kernel (vì vậy việc chập chập chảy ra khỏi giới hạn của hình ảnh). Cố gắng loại bỏ cổ vật này.

Hướng dẫn convolve image with gaussian kernel python - chuyển đổi hình ảnh với trăn hạt nhân gaussian

Sử dụng bộ lọc/kernel Gaussian để làm mịn/làm mờ hình ảnh là một công cụ rất quan trọng trong tầm nhìn máy tính. Bạn sẽ tìm thấy nhiều thuật toán sử dụng nó trước khi thực sự xử lý hình ảnh. Hôm nay chúng tôi sẽ áp dụng làm mịn Gaussian cho một hình ảnh bằng cách sử dụng Python từ đầu và không sử dụng thư viện như OpenCV.

Các bước cấp cao:

Có hai bước cho quá trình này:


  • Tạo hạt nhân/bộ lọc Gaussian
  • Thực hiện tích chập và trung bình

Kernel/bộ lọc Gaussian:

Tạo một hàm có tên gaussian_kernel(), chủ yếu lấy hai tham số. Kích thước của hạt nhân và độ lệch chuẩn.

defgaussian_kernel(size,sigma=1,verbose=False):gaussian_kernel(size,sigma=1,verbose=False):

    kernel_1D=np.linspace(-(size//2),size//2,size)kernel_1D=np.linspace(-(size// 2),size//2,size)

    foriinrange(size):foriinrange(size):

        kernel_1D[i]=dnorm(kernel_1D[i],0,sigma)kernel_1D[i] =dnorm(kernel_1D[i],0,sigma)

    kernel_2D=np.outer(kernel_1D.T,kernel_1D.T)kernel_2D=np.outer(kernel_1D.T, kernel_1D.T)

    kernel_2D*=1.0/kernel_2D.max()kernel_2D*=1.0/kernel_2D.max()

    ifverbose:ifverbose:

        plt.imshow(kernel_2D,interpolation='none',cmap='gray')plt.imshow(kernel_2D, interpolation='none',cmap='gray')

        plt.title("Image")plt.title("Image")

        plt.show()plt.show()

    returnkernel_2Dreturn kernel_2D

Tạo một vectơ có số cách đều nhau bằng cách sử dụng đối số kích thước được truyền. Khi size = 5, kernel_1D sẽ giống như sau:

array([-2.,-1.,  0.,  1.,  2.])([-2.,-1.,  0.,  1.,  2.])

Bây giờ chúng tôi sẽ gọi hàm dnorm() trả về mật độ bằng cách sử dụng độ lệch chuẩn và độ lệch chuẩn. Chúng ta sẽ thấy định nghĩa chức năng sau. Vectơ kernel_1D sẽ trông giống như:

array([0.05399097,0.24197072,0.39894228,0.24197072,0.05399097])([0.05399097,0.24197072,0.39894228,0.24197072,0.05399097])

Sau đó, chúng tôi sẽ tạo sản phẩm bên ngoài và bình thường hóa để đảm bảo giá trị trung tâm luôn là 1.

Đầu ra kernel:

Để đặt Sigma tự động, chúng tôi sẽ sử dụng phương trình sau: (Điều này sẽ hoạt động cho mục đích của chúng tôi, trong đó kích thước bộ lọc nằm trong khoảng từ 3-21):

sigma=math.sqrt(kernel_size)=math.sqrt(kernel_size)

Dưới đây là đầu ra của các kích thước kernel khác nhau.

Hướng dẫn convolve image with gaussian kernel python - chuyển đổi hình ảnh với trăn hạt nhân gaussian

Như bạn đang thấy giá trị sigma đã được đặt tự động, hoạt động tốt. Thủ thuật đơn giản này sẽ giúp bạn tiết kiệm thời gian để tìm Sigma cho các cài đặt khác nhau.

dnorm()

defdnorm(x,mu,sd):dnorm(x,mu,sd):

    return1/(np.sqrt(2*np.pi)*sd)*np.e**(-np.power((x-mu)/sd,2)/2)return1/(np.sqrt(2*np.pi) *sd)*np.e**(-np.power((x-mu)/sd,2)/2)

Đây là hàm

# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
0. Chỉ cần tính toán mật độ bằng cách sử dụng công thức của
# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
1.

Cắt tích hợp và trung bình:

Chúng tôi sẽ tạo chức năng tích chập theo cách chung để chúng tôi có thể sử dụng nó cho các hoạt động khác. Đây không phải là cách viết hiệu quả nhất để viết hàm tích chập, bạn luôn có thể thay thế bằng một cách được cung cấp bởi thư viện. Tuy nhiên, mục tiêu chính là thực hiện tất cả các hoạt động cơ bản từ đầu.

Tôi sẽ không đi chi tiết về hoạt động

# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
2 (hoặc
# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
3), vì đã có nhiều hướng dẫn tuyệt vời có sẵn. Ở đây chúng tôi sẽ chỉ tập trung vào việc thực hiện.

Hãy cùng xem xét chức năng

# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
4 từng phần.

defconvolution(image,kernel,average=False,verbose=False):convolution(image,kernel,average=False,verbose=False):

    iflen(image.shape)==3:iflen(image.shape)== 3:

& nbsp;print("Found 3 Channels : {}".format(image.shape))

        image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)image= cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;print("Converted to Gray Channel. Size : {}".format(image.shape))

    else:else:

& nbsp; & nbsp; & nbsp; & nbsp;print("Image Shape : {}".format(image.shape))

& nbsp;print("Kernel Shape : {}".format(kernel.shape))

    ifverbose:if verbose:

        plt.imshow(image,cmap='gray')plt.imshow(image,cmap='gray')

        plt.title("Image")plt.title("Image")

        plt.show()plt.show()

Hàm có hình ảnh và kernel là các tham số cần thiết và chúng tôi cũng sẽ vượt qua mức trung bình dưới dạng đối số thứ 3. Đối số trung bình sẽ chỉ được sử dụng để làm mịn bộ lọc. Lưu ý, chúng ta thực sự có thể vượt qua bất kỳ bộ lọc/kernel nào, do đó hàm này không được ghép nối/phụ thuộc vào hàm gaussian_kernel() được viết trước đó.

Vì chức năng

# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
4 của chúng tôi chỉ hoạt động trên hình ảnh với một kênh đơn, chúng tôi sẽ chuyển đổi hình ảnh thành tỷ lệ màu xám trong trường hợp chúng tôi tìm thấy hình ảnh có 3 kênh (hình ảnh màu). Sau đó vẽ hình ảnh tỷ lệ màu xám bằng cách sử dụng
# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
7.


image_row,image_col=image.shape,image_col=image.shape

kernel_row,kernel_col=kernel.shape,kernel_col=kernel.shape

output=np.zeros(image.shape)= np.zeros(image.shape)

pad_height=int((kernel_row-1)/2)=int((kernel_row-1)/2)

pad_width=int((kernel_col-1)/2)=int((kernel_col -1)/2)

padded_image=np.zeros((image_row+(2*pad_height),image_col+(2*pad_width)))=np.zeros((image_row+(2*pad_height),image_col+(2 *pad_width)))

padded_image[pad_height:padded_image.shape[0]-pad_height,pad_width:padded_image.shape[1]-pad_width]=image[pad_height:padded_image.shape[0]-pad_height,pad_width:padded_image.shape[1]- pad_width]=image

Chúng tôi muốn hình ảnh đầu ra có cùng kích thước với hình ảnh đầu vào. Điều này được gọi là kỹ thuật là

# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
8. Để làm như vậy, chúng ta cần phải đệm hình ảnh. Ở đây chúng tôi sẽ sử dụng
# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
9, chúng tôi sẽ nói về các loại đệm khác sau này trong hướng dẫn. Bây giờ đối với
# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
8, chúng ta cần tính toán kích thước của phần đệm bằng công thức sau, trong đó ../../../../data/elephant.png1 là kích thước của hạt nhân.

\ (\ frac {(k-1)} {2} \)
\frac{(k-1)}{2}
\)

Trong hai dòng cuối cùng, về cơ bản chúng ta đang tạo ra một mảng 2D trống rỗng và sau đó sao chép hình ảnh vào vị trí thích hợp để chúng ta có thể áp dụng đệm trong đầu ra cuối cùng. Trong hình ảnh dưới đây, chúng tôi đã áp dụng một phần đệm 7, do đó bạn có thể nhìn thấy đường viền màu đen.

Hướng dẫn convolve image with gaussian kernel python - chuyển đổi hình ảnh với trăn hạt nhân gaussian

Forrow Inrange (Image_Row):row inrange(image_row):

& nbsp; & nbsp; & nbsp; & nbsp; forcol inrange (Image_col):forcol inrange(image_col):

        output[row,col]=np.sum(kernel*padded_image[row:row+kernel_row,col:col+kernel_col])output[row, col]=np.sum(kernel*padded_image[row:row+kernel_row,col:col+kernel_col])

Bây giờ chỉ cần thực hiện hoạt động tích chập bằng hai vòng.

ifaverage:average:

    output[row,col]/=kernel.shape[0]*kernel.shape[1]output[row,col]/=kernel.shape[0]*kernel.shape[1]

Để áp dụng hiệu ứng mịn/mờ, chúng tôi sẽ chia pixel đầu ra cho tổng số pixel có sẵn trong hạt nhân/bộ lọc. Điều này sẽ chỉ được thực hiện nếu giá trị của trung bình được đặt ../../../../data/elephant.png2.

Cuối cùng chúng tôi được thực hiện với chức năng tích chập đơn giản của chúng tôi. Đây là hình ảnh đầu ra.

Hướng dẫn convolve image with gaussian kernel python - chuyển đổi hình ảnh với trăn hạt nhân gaussian

gaussian_blur():

Vì vậy, hàm ../../../../data/elephant.png3 sẽ gọi hàm gaussian_kernel() trước để tạo hạt nhân và sau đó gọi hàm

# Padded fourier transform, with the same shape as the image
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))

# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range
img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)
4.

defgaussian_blur(image,kernel_size,verbose=False):gaussian_blur(image,kernel_size,verbose=False):

    kernel=gaussian_kernel(kernel_size,sigma=math.sqrt(kernel_size),verbose=verbose)kernel=gaussian_kernel(kernel_size, sigma=math.sqrt(kernel_size),verbose=verbose)

    returnconvolution(image,kernel,average=True,verbose=verbose)returnconvolution(image,kernel,average=True, verbose=verbose)

main():

Trong chức năng chính, chúng ta chỉ cần gọi chức năng ../../../../data/elephant.png3 của mình bằng cách chuyển các đối số.

if__name__=='__main__':__name__=='__main__':

    ap=argparse.ArgumentParser()ap=argparse.ArgumentParser()

& nbsp; & nbsp; & nbsp; & nbsp; ap.add_argument ("-i", "-hình ảnh", bắt buộc = true, helpap.add_argument("-i", "--image",required=True,help="Path to the image")

    args=vars(ap.parse_args())args=vars(ap.parse_args())

    image=cv2.imread(args["image"])image= cv2.imread(args["image"])

    gaussian_blur(image,9,verbose=True)gaussian_blur(image,9,verbose=True)

Conclusion:

Như bạn đã nhận thấy, một khi chúng tôi sử dụng bộ lọc/kernel lớn hơn, có một đường viền màu đen xuất hiện trong đầu ra cuối cùng. Điều này là do chúng tôi đã sử dụng đệm 0 và màu của 0 là màu đen. Bạn có thể thực hiện hai chiến lược khác nhau để tránh điều này.

  • Don Tiết sử dụng bất kỳ phần đệm nào, kích thước của hình ảnh đầu ra sẽ khác nhau nhưng đã giành được bất kỳ đường viền tối nào.
  • Thay vì sử dụng đệm 0, hãy sử dụng pixel cạnh từ hình ảnh và sử dụng chúng để đệm.

Mã đầy đủ:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

Nhập khẩu Asnpnumpy asnp

importcv2cv2

Nhập khẩuMatplotlib.Pyplot Aspltmatplotlib.pyplot asplt

defconvolution(image,kernel,average=False,verbose=False):convolution(image,kernel, average=False,verbose=False):

    iflen(image.shape)==3:iflen(image.shape)==3:

& nbsp;print("Found 3 Channels : {}".format(image.shape))

        image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;print("Converted to Gray Channel. Size : {}".format(image.shape))

    else:else:

& nbsp; & nbsp; & nbsp; & nbsp;print("Image Shape : {}".format(image.shape))

& nbsp;print("Kernel Shape : {}".format(kernel.shape))

    ifverbose:ifverbose:

        plt.imshow(image,cmap='gray')plt.imshow(image,cmap='gray')

        plt.title("Image")plt.title("Image")

        plt.show()plt.show()

    image_row,image_col=image.shapeimage_row,image_col=image.shape

    kernel_row,kernel_col=kernel.shapekernel_row,kernel_col= kernel.shape

    output=np.zeros(image.shape)output=np.zeros(image.shape)

    pad_height=int((kernel_row-1)/2)pad_height=int((kernel_row-1) /2)

    pad_width=int((kernel_col-1)/2)pad_width=int((kernel_col-1)/2)

    padded_image=np.zeros((image_row+(2*pad_height),image_col+(2*pad_width)))padded_image= np.zeros((image_row+(2*pad_height),image_col+(2*pad_width)))

    padded_image[pad_height:padded_image.shape[0]-pad_height,pad_width:padded_image.shape[1]-pad_width]=imagepadded_image[pad_height:padded_image.shape[0] -pad_height,pad_width:padded_image.shape[1]-pad_width]=image

    ifverbose:ifverbose:

        plt.imshow(padded_image,cmap='gray')plt.imshow(padded_image, cmap='gray')

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;plt.title("Padded Image")

        plt.show()plt.show()

& nbsp; & nbsp; & nbsp; & nbsp; forrow inrange (Image_row):forrow in range(image_row):

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;forcol inrange(image_col):

            output[row,col]=np.sum(kernel*padded_image[row:row+kernel_row,col:col+kernel_col])output[row, col]=np.sum(kernel*padded_image[row:row+kernel_row,col:col+kernel_col])

            ifaverage:if average:

                output[row,col]/=kernel.shape[0]*kernel.shape[1]output[row,col]/=kernel.shape[0]* kernel.shape[1]

& nbsp; & nbsp; & nbsp; & nbsp; in ("kích thước hình ảnh đầu ra: {}". định dạng (output.shape))print("Output Image size : {}".format(output.shape))

    ifverbose:ifverbose:

        plt.imshow(output,cmap='gray')plt.imshow(output, cmap='gray')

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;plt.title("Output Image using {}X{} Kernel".format(kernel_row,kernel_col))

        plt.show()plt.show()

    returnoutputreturnoutput

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

Nhập khẩu Asnpnumpy asnp

importcv2cv2

Nhập khẩuargparse

Nhập khẩuMatplotlib.Pyplot Aspltmatplotlib.pyplot asplt

Nhập khẩumath

Fromcomputer_vision.gaussian_smoothing.convolution interpressConvolution Computer_Vision.Gaussian_Smoothing.convolution importconvolution

defdnorm(x,mu,sd):dnorm(x,mu,sd):

    return1/(np.sqrt(2*np.pi)*sd)*np.e**(-np.power((x-mu)/sd,2)/2)return1/ (np.sqrt(2*np.pi)*sd)*np.e**(-np.power((x-mu) /sd,2)/2)

defgaussian_kernel(size,sigma=1,verbose=False):gaussian_kernel(size,sigma=1,verbose=False):

    kernel_1D=np.linspace(-(size//2),size//2,size)kernel_1D= np.linspace(-(size//2),size//2,size)

    foriinrange(size):foriin range(size):

        kernel_1D[i]=dnorm(kernel_1D[i],0,sigma)kernel_1D[i]=dnorm(kernel_1D[i],0,sigma)

    kernel_2D=np.outer(kernel_1D.T,kernel_1D.T)kernel_2D =np.outer(kernel_1D.T,kernel_1D.T)

    kernel_2D*=1.0/kernel_2D.max()kernel_2D*=1.0/kernel_2D.max()

    ifverbose:if verbose:

        plt.imshow(kernel_2D,interpolation='none',cmap='gray')plt.imshow(kernel_2D,interpolation='none',cmap='gray')

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;plt.title("Kernel ( {}X{} )".format(size,size))

        plt.show()plt.show()

    returnkernel_2Dreturnkernel_2D

defgaussian_blur(image,kernel_size,verbose=False):gaussian_blur(image, kernel_size,verbose=False):

    kernel=gaussian_kernel(kernel_size,sigma=math.sqrt(kernel_size),verbose=verbose)kernel=gaussian_kernel(kernel_size,sigma=math.sqrt(kernel_size), verbose=verbose)

    returnconvolution(image,kernel,average=True,verbose=verbose)returnconvolution(image,kernel,average=True,verbose=verbose)

if__name__=='__main__':__name__== '__main__':

    ap=argparse.ArgumentParser()ap=argparse.ArgumentParser()

& nbsp; & nbsp; & nbsp; & nbsp; ap.add_argument ("-i", "-hình ảnh", bắt buộc = true, helpap.add_argument("-i","--image",required=True, help="Path to the image")

    args=vars(ap.parse_args())args=vars(ap.parse_args())

    image=cv2.imread(args["image"])image= cv2.imread(args["image"])

    gaussian_blur(image,5,verbose=True)gaussian_blur(image,5,verbose=True)

Dự án trong GitHub:

Vui lòng tìm dự án đầy đủ ở đây:



Làm cách nào để áp dụng bộ lọc Gaussian vào ảnh?

Một hình ảnh có thể được lọc bởi bộ lọc Gaussian đẳng hướng bằng cách chỉ định giá trị vô hướng cho Sigma. Iblur1 = imgaussfilt (i, 2); Iblur2 = imgaussfilt (i, 4); Iblur3 = imgaussfilt (i, 8); Hiển thị hình ảnh gốc và tất cả các hình ảnh được lọc. Lọc hình ảnh với hạt nhân làm mịn Gaussian dị hướng.by specifying a scalar value for sigma . Iblur1 = imgaussfilt(I,2); Iblur2 = imgaussfilt(I,4); Iblur3 = imgaussfilt(I,8); Display the original image and all the filtered images. Filter the image with anisotropic Gaussian smoothing kernels.

Làm cách nào để nhập bộ lọc Gaussian trong Python?

Thực hiện hạt nhân Gaussian trong Python..
Cú pháp: Bộ lọc (kernel).
Tham số: Hạt nhân lọc ..
Trả về: Đối tượng hình ảnh ..

Làm thế nào để bạn làm mịn một hình ảnh trong Python?

Để làm mịn một hình ảnh với một hạt nhân tùy chỉnh, chúng tôi sẽ sử dụng một hàm gọi là Filter2D () về cơ bản giúp chúng tôi kết hợp một hạt nhân được tạo tùy chỉnh với hình ảnh để đạt được các bộ lọc hình ảnh khác nhau như mài và làm mờ và nhiều hơn nữa.use a function called filter2D() which basically helps us to convolve a custom-made kernel with an image to achieve different image filters like sharpening and blurring and more.

Bộ lọc Gaussian có phải là một chập không?

Mô tả ngắn gọn.Toán tử làm mịn Gaussian là một toán tử tích chập 2 chiều được sử dụng để 'mờ' hình ảnh và xóa chi tiết và nhiễu.Theo nghĩa này, nó tương tự như bộ lọc trung bình, nhưng nó sử dụng một hạt nhân khác đại diện cho hình dạng của một gaussian ('hình chuông').The Gaussian smoothing operator is a 2-D convolution operator that is used to `blur' images and remove detail and noise. In this sense it is similar to the mean filter, but it uses a different kernel that represents the shape of a Gaussian (`bell-shaped') hump.