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

2024-04-19 15:30:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

你知道为什么会这样吗?在

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()

Tags: 图像imageimportimgpngtitleasshow
1条回答
网友
1楼 · 发布于 2024-04-19 15:30:22

你好像在为两张照片这么做?小插曲是你最好的选择。下面向您展示了如何使用它们来产生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() 

这会给你一些类似于:

matplotlib screenshot of 2x2 usage

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

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

without axis

相关问题 更多 >