【问题标题】:How do I plot an image and a graph side by side?如何并排绘制图像和图形?
【发布时间】:2017-03-11 17:16:14
【问题描述】:

我正在尝试在 Python 中使用 plt.fig() 以相等的比例并排绘制具有相应直方图的图像,但我没有得到所需的输出。相反,我将 histogram 重叠到图像上。

知道为什么这种情况不断发生吗?

import pylab as plt
import matplotlib.image as mpimg
import numpy as np


img = np.uint8(mpimg.imread('motherT.png'))
im2 = np.uint8(mpimg.imread('waldo.png'))
# convert to grayscale
# do for individual channels R, G, B, A for nongrayscale images

img = np.uint8((0.2126* img[:,:,0]) + \
        np.uint8(0.7152 * img[:,:,1]) +\
             np.uint8(0.0722 * img[:,:,2]))

im2 = np.uint8((0.2126* img[:,:,0]) + \
        np.uint8(0.7152 * img[:,:,1]) +\
             np.uint8(0.0722 * img[:,:,2]))

# show old and new image
# show original image
fig = plt.figure()

plt.imshow(img)
plt.title(' image 1')
plt.set_cmap('gray')

# show original image
fig.add_subplot(221)
plt.title('histogram ')
plt.hist(img,10)
plt.show()

fig = plt.figure()
plt.imshow(im2)
plt.title(' image 2')
plt.set_cmap('gray')

fig.add_subplot(221)
plt.title('histogram')
plt.hist(im2,10)

plt.show()

【问题讨论】:

标签: python matplotlib histogram fig


【解决方案1】:

您似乎在为两张图片这样做?子情节将是你最好的选择。下面向您展示如何使用它们来实现2 x 2 效果:

import pylab as plt
import matplotlib.image as mpimg
import numpy as np


img = np.uint8(mpimg.imread('motherT.png'))
im2 = np.uint8(mpimg.imread('waldo.png'))

# convert to grayscale
# do for individual channels R, G, B, A for nongrayscale images

img = np.uint8((0.2126 * img[:,:,0]) + np.uint8(0.7152 * img[:,:,1]) + np.uint8(0.0722 * img[:,:,2]))
im2 = np.uint8((0.2126 * im2[:,:,0]) + np.uint8(0.7152 * im2[:,:,1]) + np.uint8(0.0722 * im2[:,:,2]))

# show old and new image
# show original image
fig = plt.figure()

# show original image
fig.add_subplot(221)
plt.title(' image 1')
plt.set_cmap('gray')
plt.imshow(img)

fig.add_subplot(222)
plt.title('histogram ')
plt.hist(img,10)

fig.add_subplot(223)
plt.title(' image 2')
plt.set_cmap('gray')
plt.imshow(im2)

fig.add_subplot(224)
plt.title('histogram')
plt.hist(im2,10)

plt.show() 

这会给你类似的东西:

另请注意,在您的原始代码中,您对im2 的灰度计算使用的是img 的图像数据,而不是im2

您可能希望为每个图像关闭轴,为此您可以在每个 plt.imshow() 之前添加 plt.axis('off') 给您:

【讨论】:

  • Martin Evans 感谢您的回答,它工作得很好。我的问题是,有没有办法调整子图,使图像和直方图的大小显得更大?我更改了 add_subplot 的值,但这对图像和直方图进行了一些奇怪的更改(有时直方图被反转,图像保持不变,反之亦然)。
  • 如果是整体图大小,改成如下:fig = plt.figure(figsize=(25, 20))