以下代碼段將創建一個測驗影像
# Create 3x3x3 image
test_image = []
for i in range(9):
if i < 6:
image.append([255, 22, 96])
else:
image.append([255, 0, 0])
出去:
array([[[255, 22, 96],
[255, 22, 96],
[255, 22, 96]],
[[255, 22, 96],
[255, 22, 96],
[255, 22, 96]],
[[255, 0, 0],
[255, 0, 0],
[255, 0, 0]]], dtype=int32)
我的目標是為 test_image 中的每個 [255、22、96] 創建零的單通道影像,我想在新的 single_channel 影像中設定數字 100:
我嘗試了以下內容:
test_image = np.array(test_image)
height, width, channels = test_image.shape
single_channel_img = np.zeros(test_image.shape, dtype=int)
msk = test_image == [255, 22, 96] # DOES NOT WORK AS EXPECTED
single_channel_img[msk] = 100
這不起作用,因為屏蔽的結果:
msk = test_image == [255, 22, 96]
回報:
array([[[ True, True, True],
[ True, True, True],
[ True, True, True]],
[[ True, True, True],
[ True, True, True],
[ True, True, True]],
[[ True, False, False],
[ True, False, False],
[ True, False, False]]])
為什么掩蔽會為最后 3 個像素回傳 True,我如何才能確保只有當所有 3 個值都相同時比較才回傳 True?我的假設是,當所有 3 個 RGB 值都等于 [255、22、96] 時,我屏蔽的方式應該只回傳 True。
uj5u.com熱心網友回復:
您可以msk使用陣列廣播轉換為 3-D 陣列:
https ://numpy.org/doc/stable/user/basics.broadcasting.html
該命令.reshape可用于更改陣列的維度。Numpy 將自動填充“薄”維度。因此,例如,比較陣列與形狀(n,n,3)和(1,1,3)比較每個子陣列test_image[i,j,:]與目標相同(1,1,3)。
import numpy as np
# Create 3x3x3 image
test_image = []
for i in range(9):
if i < 6:
test_image.append([255, 22, 96])
else:
test_image.append([255, 0, 0])
test_image = np.array(test_image).reshape((3,3,3)) # test image shape needed to be fixed
single_channel_img = np.zeros(test_image.shape, dtype=int)
msk = test_image == np.array([255,22,96]).reshape((1,1,3)) # now it works
single_channel_img[msk] = 100
print(single_channel_img)
# [[[100 100 100]
# [100 100 100]
# [100 100 100]]
#
# [[100 100 100]
# [100 100 100]
# [100 100 100]]
#
# [[100 0 0]
# [100 0 0]
# [100 0 0]]]
附言。PyTorch 也有陣列廣播,在深度學習中非常有用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/536325.html
上一篇:如何隔離這些影像中的電容器?
