保存的图片有白边_plt 图片按像素尺寸保存并消除白边

这段代码主要用于解决plt图片在保存时出现白边的问题,并能根据指定的像素尺寸和DPI分辨率精确保存图片,确保最终效果。
摘要由CSDN通过智能技术生成
# 加载相关库及图片
from google.colab import drive
import matplotlib.pyplot as plt
import numpy as np
drive.mount('/content/drive')
from glob import glob
mask_pth=glob('/content/drive/My Drive/Colab Notebooks/data_nifti/rgb_B2_patch02/PNG/'+'*.png')[3]

## plt保存去除白边 并且按照pixel*pixel格式输出 (figsize和dpi共同控制)
# fig = plt.gcf()
# fig.set_size_inches(16,16) #dpi = 100, output = 1600*1600 pixels inch (width,height)=(16,16)
plt.figure(figsize=(16,16),dpi=100)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
plt.margins(0,0)    
mask_ins=plt.imread(mask_pth)    
plt.imshow(mask_ins)
plt.savefig('/content/example.png',pad_inches=0)  # dpi=100 和上文相对应 pixel尺寸/dpi=inch尺寸
plt.show()                 # 此处顺序不能弄反 imshow(),savefig(),show()
#plt.clf()                  #plt.clf()的作用:用于批量存储图片时 每一次显示图片并保存以后,释放图窗,接受下一个图片显示和存储

此段代码的主要作用:

1)消除plt图片保存时的白边

2)按照像素尺寸和dpi分辨率要求,保存图片

最终图片效果:

5d455c51def25951bb31e9aec8294b3f.png
def img_cut_roi_resize_to_target_black(img_txt_path,result_path): img_total = [] txt_total = [] file = os.listdir(img_txt_path) for filename in file: first, last = os.path.splitext(filename) if last == ".bmp": # 图片的后缀名 img_total.append(first) # print(img_total) else: txt_total.append(first) for img_ in img_total: if img_ in txt_total: filename_img = img_ + ".bmp" # 图片的后缀名 # print('filename_img:', filename_img) path1 = os.path.join(img_txt_path, filename_img) img = cv2.imread(path1) h, w = img.shape[0], img.shape[1] # 直接读取原图的长宽不会失真 img = cv2.resize(img, (w, h), interpolation=cv2.INTER_CUBIC) # resize 图像大小,否则roi区域可能会报错 # plt.imshow('resized_img',img) # 会报错,之后再次查看resize后的图片(已解决) # plt.show() filename_txt = img_ + ".txt" # print('filename_txt:', filename_txt) n = 1 with open(os.path.join(img_txt_path, filename_txt), "r+", encoding="utf-8", errors="ignore") as f: for line in f: aa = line.split(" ") x_center = w * float(aa[1]) # aa[1]左上点的x坐标 y_center = h * float(aa[2]) # aa[2]左上点的y坐标 width = int(w * float(aa[3])) # aa[3]图片width height = int(h * float(aa[4])) # aa[4]图片height lefttopx = int(x_center - width / 2.0) lefttopy = int(y_center - height / 2.0) # roi = img[lefttopy+1:lefttopy+height+3,lefttopx+1:lefttopx+width+1] # [左上y:右下y,左上x:右下x] (y1:y2,x1:x2)需要调参,否则裁剪出来的小图可能不太好 roi = img[lefttopy:lefttopy + height, lefttopx:lefttopx + width] # 目前没有看出差距 roi = img_resize_to_target_black(roi) # roi = cv2.copyMakeBorder(roi, 50, 50, 50, 50, cv2.BORDER_CONSTANT, value=[255, 255, 255]) # 是将原图长宽各个
05-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值