如何向量化for循环numpy.where

wwwo4jvm  于 2023-04-06  发布在  其他
关注(0)|答案(1)|浏览(369)

我是numpy的新手,目前无法在下面的代码中向量化for循环:

# Build an image_array by label discrimination, using seg and seg_4col, expanding discrimated labels in the process to fillflood the image
# lab arg being one of the 4 labels of the 4 colored seg (seg_4col)
def img_4c_d(lab, img):

    seg_islands = np.where(seg_4col == lab, seg, 0)
    seg_exp = expand_labels(seg_islands, distance=max(img.shape[0], img.shape[1]))

    unique_labels = unique(np.ravel(seg_exp))
    color_dic = np.zeros((np.max(unique_labels) + 1, 3), dtype=np.uint8)

    for label in unique_labels:
        d = img[np.where(seg_islands == label)]

        color_dic[label] = [np.argmax(np.bincount(d[...,0])),
                            np.argmax(np.bincount(d[...,1])),
                            np.argmax(np.bincount(d[...,2]))]

    return color_dic[seg_exp]

unique_labels可以保存数千个值,您可以很容易地猜到它的性能有多差。
我已经尽力了,但没有成功,如果有人能帮上忙,我非常感谢。

fivyi3re

fivyi3re1#

您可以使用scipy.ndimage.find_objects来获得每个标签周围的较小边界框。find_objects函数只需通过图像一次即可完成此操作。这将使抓取该标签的像素更快,特别是如果您的对象很紧凑:

from scipy.ndimage import find_objects  # NEW

# Build an image_array by label discrimination, using seg and seg_4col, expanding discrimated labels in the process to fillflood the image
# lab arg being one of the 4 labels of the 4 colored seg (seg_4col)
def img_4c_d(lab, img):

    seg_islands = np.where(seg_4col == lab, seg, 0)
    seg_exp = expand_labels(seg_islands, distance=max(img.shape[0], img.shape[1]))

    unique_labels = unique(np.ravel(seg_exp))
    color_dic = np.zeros((np.max(unique_labels) + 1, 3), dtype=np.uint8)
    bounding_boxes = find_objects(seg_islands)  # NEW

    for label in unique_labels:
        boxed = img[bounding_boxes[label]]  # NEW
        d = boxed[boxed == label]  # NEW; note np.where was redundant here

        color_dic[label] = [np.argmax(np.bincount(d[...,0])),
                            np.argmax(np.bincount(d[...,1])),
                            np.argmax(np.bincount(d[...,2]))]

    return color_dic[seg_exp]

注意:这也是skimage.measure.regionprops的工作方式,您可以使用extra_properties=参数来实现相同的目标。

相关问题