我堅持應該相當直截了當,但其他未解決的問題并沒有解決我遇到的完全相同的問題。
我正在嘗試根據布爾蒙版裁剪影像。我可以這樣做:
# crop image based on segmentation mask
def get_segment_crop(img,tol=0, mask=None):
for i in range(mask.shape[2]):
crops = []
if mask is None:
mask = img > tol
for i in range(mask.shape[2]):
crops.append(img[np.ix_(mask[:,:,i].any(1), mask[:,:,i].any(0))])
return crops
(此函式輸入 RGB 影像(w,h,c)和True/False形狀的掩碼(w,h,n)并在每個分割掩碼周圍裁剪一個邊界框)。但后來我想嘗試洗掉裁剪輸出的每個分割蒙版周圍的背景(即設定所有不True為)(蒙版分割是形狀 - 不是完美的矩形)。0我認為先洗掉背景然后裁剪可以作業,但我堅持洗掉背景部分,因為我的影像有 3 個通道。
這是一個作業示例,到目前為止我已經嘗試過將我面臨的問題嵌入為評論。
import numpy as np
from scipy import misc
import matplotlib.pyplot as plt
file = misc.face()
img = np.array(file)
#create random masks
tf_mask = np.full((img.shape[0], img.shape[1], 2), False)
tf_mask[500:600,500:600,0] = True
tf_mask[500:650, 550:700, 0] = True
tf_mask[100:200, 100:200, 1] = True
tf_mask[200:300, 100:150, 1] = True
# np.where(tf_mask[:,:,0])[0] #sanity check True values were inputed
# Trying to set all values in img where masks=False to 0. Problem: it saves over original img array so the next mask doesn't display region of interest from original image
for i in range(tf_mask.shape[2]):
img[tf_mask[:,:,i]==False] = 0
plt.imshow(img)
plt.show()
# issue with this: image is 3 channels so need to iterate over all channels but how to then merge back?
for i in range(tf_mask.shape[2]):
for j in range(3):
new_img = np.where(tf_mask[:,:, i]==False, 0, img[:,:,j])
plt.imshow(new_img)
plt.show()
感謝您提供解決此問題的想法,或者是否有更簡潔的方法來解決此問題。
uj5u.com熱心網友回復:
如果您在單個 3d 陣列中有多個蒙版,其中前兩個維度與影像相同,并且各個蒙版堆疊在第三個維度中,請首先沿第三個維度折疊蒙版,然后將其與影像相乘。
假設您想要保留一個像素,如果它在任何掩碼中為 True:
mask = np.any(mask,axis=-1)
masked = mask[:,:,None] * img
import numpy as np
rng = np.random.default_rng()
a = np.ones((3,3,3))
b = rng.integers(0,1,(3,3,2),endpoint=True,dtype=bool)
>>> a
array([[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]])
>>> b
array([[[ True, False],
[False, True],
[False, False]],
[[False, True],
[False, False],
[ True, True]],
[[False, True],
[ True, True],
[ True, True]]])
>>> b[0,0,:]
array([ True, False])
>>> b[0,1,:]
array([False, True])
>>> b[0,2,:]
array([False, False])
>>> b = np.any(b,axis=-1)
>>> b[0,0]
True
>>> b[0,1]
True
>>> b[0,2]
False
>>> a * b[:,:,None]
array([[[1., 1., 1.],
[1., 1., 1.],
[0., 0., 0.]],
[[1., 1., 1.],
[0., 0., 0.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]])
uj5u.com熱心網友回復:
為什么要先創建面具?
如果您手動輸入掩碼范圍值,只需使用這些值來索引您的陣列:
img = img[500:600,500:600,:]
如果您堅持使用蒙版,您可以將蒙版乘以您的 img,但請確保您的蒙版和 img 具有相同的形狀。
img = img * 掩碼。您將獲得掩碼 == True 和 0 的值,其中掩碼 == False
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/494389.html
