以下 Python 腳本計算 .jpg 影像的藍色通道的 2D 卷積:
- 它讀取 6x6 BGR 影像:
![[cv2.filter2D() on Python]:為什么它會回傳這些特定的值?](https://i.stack.imgur.com/rTYDm.jpg)
- 它提取通道 0。在 cv2 中,這對應于顏色通道藍色。
- 我列印通道的值
- 輸入資料型別為 uint8。因此,我們制作 cv2.filter2D() 并設定 ddepth=-1,輸出也將具有資料型別 uint8,因此無法表示 >255 的值。因此,我決定將影像從 uint8 轉換為例如 short 以具有更寬的數值范圍并能夠表示過濾器輸出處的值。
- 我定義了一個大小為 3x3 的內核(請參閱下面代碼中的內核值)。
- 我用內核過濾藍色通道,由于填充,我獲得了相同大小的過濾影像
- 函式 filter2D() 給出的過濾值不符合我的預期。例如,對于左上角的值,函式回傳 449,但是我本來希望 425 代替,因為 71*0 60*0 65*1 69*1 58*3 61*1 89*0 66 *0 56*1=425。
有誰知道過濾后的影像是如何通過filter2D()函式計算的?我提出的計算有什么問題嗎?
import cv2
import numpy as np
image = cv2.imread('image.jpg')
# Read image 6x6x3 (BGR)
blue_channel=image[:,:,0]
# Obtain blue channel
print(blue_channel)
# Result is:
#[[71 60 65 71 67 67]
# [69 58 61 69 69 67]
# [89 66 56 55 45 37]
# [65 37 27 32 31 30]
# [46 23 22 38 43 45]
# [55 36 44 60 60 47]]
blue_channel=np.short(blue_channel)
# Convert image from uint8 to short. Otherwise, output of the filter will have the same data type as the
# input when using ddepth=-1 and hence filtered values >255 won't be able to be represented
print(blue_channel)
# Result is (same as before, ok...):
# 71 60 65 71 67 67
# 69 58 61 69 69 67
# 89 66 56 55 45 37
# 65 37 27 32 31 30
# 46 23 22 38 43 45
# 55 36 44 60 60 47
kernel=np.array([ [0, 0, 1], [1, 3, 1], [0, 0, 1] ])
# Kernel is of size 3x3
# [0 0 1]
# [1 3 1]
# [0 0 1]
filtered_image = cv2.filter2D(blue_channel, -1, kernel)
# Blue channel is filtered with the kernel and the result gives:
# 449 438 464 483 473 473
# 449 425 436 449 447 451
# 494 431 390 366 324 301
# 358 281 243 242 237 240
# 257 208 219 270 289 312
# 283 251 304 370 377 347
print(filtered_image)
# Why top left filtered value is 449?
# I would expect this:
# 71*0 60*0 65*1 69*1 58*3 61*1 89*0 66*0 56*1=425
# In short, I would expect 425 instead of 449, how is that 449 computed?
uj5u.com熱心網友回復:
您的計算沒有錯,但是您實際上已經為 [2,2] 處的值撰寫了卷積,這與您的結果 425 匹配。
要計算值,例如 [1,1],您需要影像之外的值,您必須處理周圍的邊緣。默認情況下,在函式filter2D中,它們被處理為reflect 101,在 wiki 中,其移動鏡像邊緣處理為 1。
要了解 mirror(reflect) 和 reflect 101 之間的差異:
鏡子(反射)
left edge | image | right edge
| |
b a | a b c | c b
反映 101
left edge | image | right edge
| |
c b | a b c | b a
因此,在 filder2D 中使用默認邊緣處理計算 [1,1] 將是:
0*58 0*69 1*58 1*60 3*71 1*60 0*58 0*69 1*58 = 449
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/529392.html
