在 numpy 中将 2 个图像堆叠在一起

stack 2 images together in numpy

当 1 张图像通过时,从下面的 codw 得到的形状是 (1,3,640,640)。

def shape(im1):
    image_src = Image.open(im1)
    print('Loaded Image Info : ',image_src.format, image_src.size, image_src.mode) # size order : width*height

    # Resize to img_size_w, img_size_h
    resized =  image_src.resize((640, 640))   # To be imblemnated : letterbox_image(image_src, (img_size_w, img_size_h))
    print('After resizing :' ,resized.size, resized.mode) # size order : width*height
    #display(resized)

    # Preprocess the image
    img_in = np.transpose(resized, (2, 0, 1)).astype(np.float32)  # HWC -> CHW
    img_in = np.expand_dims(img_in, axis=0) # Add redundant dimension for batch-size (Assumed to be 1, check batch_size = session.get_inputs()[0].shape[0])
    img_in /= 255.0 # Normalize all pixels
    print('Batch-Size, Channel, Height, Width : ',img_in.shape)
    return img_in

如何更改代码,以便在传递 2 张图像时将它们堆叠在一起并给出形状 (2,3,640,640)。

尝试np.concatenate

out = np.concatenate([im1, im2], axis=0)

您可以将 NumPy 数组附加到列表中,并在末尾将列表转换为数组。

  • 用可变参数定义你的方法:

     def shape(*args):
    
  • 迭代参数,并将图像附加到列表中:

     imgs_list = []  # List of images (initialize to an empty list)
    
     for im in args:
         image_src = Image.open(im)
    
         ...
    
         imgs_list.append(img_in)  # Append image to list
    
  • 将列表转换为 NumPy 数组,规范化并 return 结果:

     imgs_in = np.array(imgs_list)  # Convert the list to NumPy array    
     imgs_in /= 255.0 # Normalize all pixels
     return imgs_in
    

shape 方法的更新代码:

def shape(*args):
    imgs_list = []  # List of images (initialize to an empty list)

    # Iterate all function arguments
    for im in args:
        image_src = Image.open(im)
        print('Loaded Image Info : ',image_src.format, image_src.size, image_src.mode) # size order : width*height

        # Resize to img_size_w, img_size_h
        resized =  image_src.resize((640, 640))   # To be implemented: letterbox_image(image_src, (img_size_w, img_size_h))
        print('After resizing :' ,resized.size, resized.mode) # size order : width*height
        #display(resized)

        # Preprocess the image
        img_in = np.transpose(resized, (2, 0, 1)).astype(np.float32)  # HWC -> CHW

        imgs_list.append(img_in)  # Append image to list


    #img_in = np.expand_dims(img_in, axis=0) # Add redundant dimension for batch-size (Assumed to be 1, check batch_size = session.get_inputs()[0].shape[0])

    imgs_in = np.array(imgs_list)  # Convert the list to NumPy array    

    imgs_in /= 255.0 # Normalize all pixels
    print('Batch-Size, Channel, Height, Width : ',imgs_in.shape)

    return imgs_in

用法:

res = shape('image1.png', 'image2.png', 'image3.png')