为什么 Matplotlib 显示不正确的图像?
Why does Matplotlib shows an incorrect image?
我正在尝试将图像分成小块并将其可视化,但 matplotlib 一直显示完全不正确的输出。
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)
我使用的方法如下:
imgcrop("cats.jpeg", 14, 14)
我得到了 16 x 16
个补丁,但颜色与图片完全不同
代码来源:#How to Split Image Into Multiple Pieces in Python
输入:
输出:
你的问题不是颜色不对,而是你只看到显示的图像的最后一个补丁(至少在 jupyter notebook 中 运行 时)
这导致唯一可见的补丁是地面之一(右下角),它完全是棕色阴影,因此看起来与您的初始图片非常不同。
最简单的修复方法是使用 plt.subplots
绘制所有补丁:
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)
输入:
输出:
我正在尝试将图像分成小块并将其可视化,但 matplotlib 一直显示完全不正确的输出。
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)
我使用的方法如下:
imgcrop("cats.jpeg", 14, 14)
我得到了 16 x 16
个补丁,但颜色与图片完全不同
代码来源:#How to Split Image Into Multiple Pieces in Python
输入:
输出:
你的问题不是颜色不对,而是你只看到显示的图像的最后一个补丁(至少在 jupyter notebook 中 运行 时)
这导致唯一可见的补丁是地面之一(右下角),它完全是棕色阴影,因此看起来与您的初始图片非常不同。
最简单的修复方法是使用 plt.subplots
绘制所有补丁:
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)
输入:
输出: