matplotlib 使用 plt.savefig() 输出图片去除旁边的空白区域

在网上查了很多答案,最终得到的效果都不是很理想,最终根据自己的情况进行了更改:

pyplot.axis('off') #增加这行关闭坐标轴显示,但仍有空白区域
#关键在于bbox_inches = 'tight',pad_inches = 0,去掉空白区域
pyplot.savefig(save_dir,bbox_inches = 'tight',pad_inches = 0)

完整代码:

def detect_save(im_array,model,save_dir):
   yhat = model.detect(im_array, verbose=0)[0]
   pyplot.imshow(im_array[0])
   ax = pyplot.gca()
   # 绘制每个绘图框
   class_ids = yhat['class_ids']
   index = 0
   for box in yhat['rois']:
      # 获取坐标
      y1, x1, y2, x2 = box
      # 计算绘图框的宽度和高度
      width, height = x2 - x1, y2 - y1
      # 创建形状对象
      if class_ids[index] == 1:
         rect = Rectangle((x1, y1), width, height, fill=False, color='green')
      if class_ids[index] == 2:
         rect = Rectangle((x1, y1), width, height, fill=False, color='red')
      # 绘制绘图框
      ax.add_patch(rect)
      index += 1
   # 显示绘制结果
   pyplot.axis('off')  #去除空白区域
   pyplot.savefig(save_dir,bbox_inches = 'tight',pad_inches = 0)
   pyplot.clf()

效果展示:

增加前:
在这里插入图片描述

增加后:

3FxXzQzMzgxMDEw,size_16,color_FFFFFF,t_70)

  • 14
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值