Python 如何调整子批次';紧密贴合的高度和宽度?
我有一个代码,可以把一张图片分成几个部分,我想把它们一起打印出来(在它们之间留一个小空间),但要保留相同的大小,这样完整的图片仍然清晰可见Python 如何调整子批次';紧密贴合的高度和宽度?,python,matplotlib,subplot,Python,Matplotlib,Subplot,我有一个代码,可以把一张图片分成几个部分,我想把它们一起打印出来(在它们之间留一个小空间),但要保留相同的大小,这样完整的图片仍然清晰可见 def crop_image(img, quadrant): img = img_to_array(img) d = img.shape rows = int(d[0]*2/3) cols = int(d[1]*2/3) q = {"TL": img[:rows,:cols,:], "TR": img
def crop_image(img, quadrant):
img = img_to_array(img)
d = img.shape
rows = int(d[0]*2/3)
cols = int(d[1]*2/3)
q = {"TL": img[:rows,:cols,:],
"TR": img[:rows,cols:,:],
"BL": img[rows:,:cols,:],
"BR": img[rows:,cols:,:]}
return array_to_img(q[quadrant])
img = load_img('./example1.jpeg', target_size=(224, 224))
cropped = crop_image(img, 'TR')
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2)
ax1.imshow(crop_image(img, 'TL'))
ax1.axis('off')
ax2.imshow(crop_image(img, 'TR'))
ax2.axis('off')
ax3.imshow(crop_image(img, 'BL'))
ax3.axis('off')
ax4.imshow(crop_image(img, 'BR'))
ax4.axis('off')
fig.subplots_adjust(hspace=0.1)
plt.tight_layout()
子地块高度和宽度之间的比率需要正好是图形各个部分的行数和列数之间的比率 这可以通过正在使用的gridspec的
高度/宽度比
和宽度/宽度比
参数来实现
import matplotlib.pyplot as plt
img = plt.imread("https://i.stack.imgur.com/9qe6z.png")
d = img.shape
rows = int(d[0]*2/3)
cols = int(d[1]*2/3)
q = {"TL": img[:rows,:cols,:],
"TR": img[:rows,cols:,:],
"BL": img[rows:,:cols,:],
"BR": img[rows:,cols:,:]}
kw = dict(height_ratios=[rows, d[0]-rows], width_ratios=[cols, d[1]-cols])
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2, gridspec_kw=kw)
ax1.imshow(q['TL'])
ax2.imshow(q['TR'])
ax3.imshow(q['BL'])
ax4.imshow(q['BR'])
for ax in (ax1, ax2, ax3, ax4):
ax.axis("off")
fig.subplots_adjust(hspace=0.1)
plt.show()