Issue
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:
Output:
Solution
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:
Output:
Answered By - FlyingTeller
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.