如何并排绘制图像和图形?

Bra*_*n J 2 python matplotlib histogram fig

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

知道为什么会这样吗?

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()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ans 5

您似乎是为两张图片执行此操作?子图将是你最好的选择。下面向您展示如何使用它们来实现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() 
Run Code Online (Sandbox Code Playgroud)

这会给你类似的东西:

2x2 使用的 matplotlib 截图

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

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

无轴

  • 如果您指的是整体图形大小,只需将其更改如下:`fig = plt.figure(figsize=(25, 20))` (2认同)