我有一個 numpy 陣列img(640, 400, 3)它基本上包含通過 OpenCV 庫加載的影像的像素陣列。一些像素是零[0, 0, 0],其他是非零[r, g, b]值
我如何能 -
- 插入另一列以使其形狀為(640, 400, 4)以添加 alpha 值,使像素變為[r, g, b, a],其中a是 alpha 值
- 在這個新列中,需要根據以下條件設定alpha值: if [r, g, b] == 0 then alpha == 0 else alpha == 255。即,我的新像素應該是[0, 0, 0, 0]或[r, g, b, 255]
我如何在 numpy 本身中執行此操作,我不想使用 OpenCV 重新讀取影像以生成 alpha 值。
uj5u.com熱心網友回復:
rgb = np.random.uniform(0, 255, (100, 100, 3)).astype("uint")
# example position with [0,0,0]
rgb[0, 0, :] = 0
# mask where condition is satisfied
msk = np.sum(rgb, axis=2)==0
# Prep the alpha layer
nrows, ncols, _ = rgb.shape
alpha = np.ones((nrows, ncols), dtype="uint") * 255
# Make positions that satisfy condition equal to 0
alpha[msk]= 0
# add extra alpha layer
rgba = np.dstack([rgb, alpha])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427046.html
下一篇:洗掉字典串列中得分低的重復項
