方法1
这是
views和
np.searchsorted-
# https://stackoverflow.com/a/45313353/ @Divakardef view1D(a, b): # a, b are arrays a = np.ascontiguousarray(a) b = np.ascontiguousarray(b) void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1])) return a.view(void_dt).ravel(), b.view(void_dt).ravel()# Trace back a 2D array back to given labelsdef labelrows(a2D, label_list): # Reduce array and labels to 1D a1D,b1D = view1D(a2D, label_list) # Use searchsorted to trace back label indices sidx = b1D.argsort() return sidx[np.searchsorted(b1D, a1D, sorter=sidx)]
因此,要将其用于
3D图像阵列,我们需要将高度和宽度合并为一个维度,并使颜色通道保持原样暗淡,并使用标签功能。
方法#2
针对具有
[0,255]范围的图像元素进行了调整,我们可以利用矩阵乘法来降低维数,从而进一步提高性能,就像这样-
def labelpixels(img3D, label_list): # scale array s = 256**np.arange(img.shape[-1]) # Reduce image and labels to 1D img1D = img.reshape(-1,img.shape[-1]).dot(s) label1D = np.dot(label_list, s) # Use searchsorted to trace back label indices sidx = label1D.argsort() return sidx[np.searchsorted(label1D, img1D, sorter=sidx)]
样本运行如何扩展图像大小并验证-
In [194]: label_list = [[0,255,255], [0,0,0], [0,0,255], [255, 0, 255]]In [195]: idx = [2,0,3,1,0,3,1,2] # We need to retrieve this backIn [196]: img = np.asarray(label_list)[idx].reshape(2,4,3)In [197]: imgOut[197]: array([[[ 0, 0, 255], [ 0, 255, 255], [255, 0, 255], [ 0, 0, 0]], [[ 0, 255, 255], [255, 0, 255], [ 0, 0, 0], [ 0, 0, 255]]])In [198]: labelrows(img.reshape(-1,img.shape[-1]), label_list)Out[198]: array([2, 0, 3, 1, 0, 3, 1, 2])In [217]: labelpixels(img, label_list)Out[217]: array([2, 0, 3, 1, 0, 3, 1, 2])
最后,输出需要重新调整为
2D-
In [222]: labelpixels(img, label_list).reshape(img.shape[:-1])Out[222]: array([[2, 0, 3, 1], [0, 3, 1, 2]])
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)