-1

I am trying to divide an image into patches and visualize it but matplotlib keep showing totally incorrect output.

from PIL import Image
import os
def imgcrop(input, xPieces, yPieces):
    filename, file_extension = os.path.splitext(input)
    im = Image.open(input)
    imgwidth, imgheight = im.size
    height = imgheight // yPieces
    width = imgwidth // xPieces
    for i in range(0, yPieces):
        for j in range(0, xPieces):
            box = (j * width, i * height, (j + 1) * width, (i + 1) * height)
            a = im.crop(box)
            np_img = np.asarray(a)
            plt.imshow(np_img)

I used the method as follows:

imgcrop("cats.jpeg", 14, 14)

I got a 16 x 16 patches but in different colours entirely different from the image

code credit: #How to Split Image Into Multiple Pieces in Python

Input:

enter image description here

Output:

enter image description here

FlyingTeller
  • 17,638
  • 3
  • 38
  • 53
Craving_gold
  • 189
  • 1
  • 14
  • Can you share your input data and output that you get as well? – FlyingTeller Jan 24 '22 at 07:53
  • Input and output data have been added to the question. What I want is to divide an image into patches in a way that I can have access to the pixels of each patch for manipulation. – Craving_gold Jan 24 '22 at 08:09

1 Answers1

0

Your issue is not that the color is wrong, but that you are only seeing the very last patch of your image being displayed (at least when run in jupyter notebook)

This results in the only patch visible being one of the ground (lower right corner), which is completely in shades of brown and does therefore look very different to your initial picture.

The easiest fix is to use plt.subplots to plot all patches:

from PIL import Image
import os
import numpy as np
import matplotlib.pyplot as plt
def imgcrop(input, xPieces, yPieces):
    filename, file_extension = os.path.splitext(input)
    im = Image.open(input)
    imgwidth, imgheight = im.size
    height = imgheight // yPieces
    width = imgwidth // xPieces
    fig, axs = plt.subplots(yPieces, xPieces)
    for i in range(0, yPieces):
        for j in range(0, xPieces):
            box = (j * width, i * height, (j + 1) * width, (i + 1) * height)
            a = im.crop(box)
            np_img = np.asarray(a)
            axs[i][j].imshow(np_img)
    [axi.set_axis_off() for axi in axs.ravel()]
imgcrop("cat.jpg", 14, 14)

Input:

enter image description here

Output:

enter image description here

FlyingTeller
  • 17,638
  • 3
  • 38
  • 53