【问题标题】:How to extract patches from an image in pytorch/tensorflow into 4 equal parts?如何从 pytorch/tensorflow 中的图像中提取补丁成 4 个相等的部分?
【发布时间】:2022-01-19 11:01:57
【问题描述】:

我使用的是 16x16 彩色图像;我为此编写了小代码,但无法准确执行。

import numpy as np
from patchify import patchify
image = cv2.imread('subbu_i.jpg')
print(image.shape)
patches = patchify(image, (4,4), step=1) 
print(patches.shape)

请帮忙。

【问题讨论】:

    标签: python tensorflow pytorch


    【解决方案1】:

    对于 TensorFlow,请尝试 tf.image.extract_patches

    import tensorflow as tf
    from PIL import Image
    import matplotlib.pyplot as plt
    import numpy as np
    
    image = Image.open('/content/image.png')
    plt.imshow(image)
    
    image = tf.expand_dims(np.array(image), 0)
    image = tf.expand_dims(np.array(image), -1)
    patches = tf.image.extract_patches(images=image,
                            sizes=[1, 4, 4, 1],
                            strides=[1, 4, 4, 1],
                            rates=[1, 1, 1, 1],
                            padding='VALID')
    
    axes=[]
    fig=plt.figure()
    
    for i in range(4):
        axes.append( fig.add_subplot(2, 2, i + 1) )
        subplot_title=("Patch "+str(i + 1))
        axes[-1].set_title(subplot_title)  
        patch = tf.reshape(patches[0, i, i], (4, 4))
        plt.imshow(patch)
    fig.tight_layout()    
    plt.show()
    

    【讨论】:

    • 你完全错了。您说您的问题中有 16x16 彩色图像,而不是 1x248x255x4x1。代码不适用于您正在尝试的图像,这对您来说不是很明显吗?哦,我正在加载一个真实的图像,如我发布的代码 sn-p 的开头所示。
    【解决方案2】:
    import tensorflow as tf
    from PIL import Image
    import matplotlib.pyplot as plt
    import numpy as np
    
    image = Image.open('/content/drive/MyDrive/subbu_i16.jpg')
    plt.imshow(image)
    
    image = tf.expand_dims(np.array(image),0) # To create the batch information
    patches = tf.image.extract_patches(images=image,
                                       sizes=[1, 4, 4, 1],
                                       strides=[1, 4, 4, 1],
                                       rates=[1, 1, 1, 1],
                                       padding='VALID')
    plt.figure(figsize=(10, 10))
    for imgs in patches:
        count = 0
        for r in range(2):
            for c in range(2):
                ax = plt.subplot(2, 2, count+1)
                plt.imshow(tf.reshape(imgs[r,c],shape=(4,4,3)).numpy().astype("uint8"))
                count += 1
    

    sample image result images 谢谢@alonetogether

    【讨论】:

      猜你喜欢
      • 2020-08-22
      • 1970-01-01
      • 2021-01-20
      • 2018-01-31
      • 1970-01-01
      • 2017-07-09
      • 2020-05-05
      • 2019-06-17
      • 2023-03-19
      相关资源
      最近更新 更多