简体   繁体   中英

How to extract patches from an image in pytorch/tensorflow into 4 equal parts?

I am using a 16x16 colour image; I wrote small code for that but could not perform it precisely.

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)

Please help.

For Tensorflow, try 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()

在此处输入图像描述 在此处输入图像描述

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 Thank you @alonetogether

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM