目标检测------图片预处理/方框绘图(pillow,matplotlib,tensorboard)

实验环境:win10 + pytorch1.5(cpu版) + tensorboard2.2.0 + Pillow7.1.2 + matplotlib3.2.1 + numpy1.16.4mkl版

Pillow读入图片

PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。由于PIL仅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了许多新特性,因此,我们可以直接安装使用Pillow。 Pillow官方文档

读入图片:
在目标检测任务中,通常会将一张RGB模式的图片读入转换成numpy格式,期间可能还会对图片进行重采样(放大、缩小)等操作。在pytorch框架中,通常采用Pillow库进行相关操作。

import numpy as np
from PIL import Image
import PIL

f = Image.open("E:\PASCAL2007\VOC2007\JPEGImages\000001.jpg")  
#f.show()  #可以直接调用此方法在桌面显示当前此图片
#图片缩放1/2,采用BICUBIC重采样算法(默认值)
f_resized = f.resize(size = (f.width // 2, f.height // 2),resample = PIL.Image.BICUBIC)
#将PIL格式转换成numpy格式
img_np = np.asarray(f_resized ,dtype=np.float32)  #H,W,C格式 
# f = Image.fromarray(img_np)  #numpy格式转PIL格式

相关重采样算法具体原理。更多使用方法参见Pillow官方文档 。

matplotlib绘图并加上方框标注,将结果显示在tensorboard中

通常在目标检测任务,需要将最终的预测结果绘制方框后进行可视化展示,通常采用matplotlib库进行处理,有时并且还会将结果显示在tensorboard中进行可视化。
Matplotlib 简单入门 , matplotlib官方文档 ,pyotrch中的tensorboard使用
注: 下面代码用到了上面代码的变量。若要使用plot.show(),则要放在tensorboard写入完成后使用,否则可能会报错。

import matplotlib
#matplotlib.use('Agg')   #采用Agg作为matplotlib绘制后端,是一种非交互式的后端,调用plot.show()后不会在桌面显示图片,在无桌面程序的服务器中运行程序时可使用此代码。
from matplotlib import pyplot as plot
from torch.utils.tensorboard import SummaryWriter  
#将img_np数据通过matplot展示
fig = plot.figure()   #相当于创建画板
ax = fig.add_subplot(1,1,1)   #创建子图,相当于在画板中添加一个画纸,当然可创建多个画纸,具体由其中参数而定。
ax.imshow(img_np.astype(np.uint8))  #当前画纸中画一个图片

#添加方框,(4,5)表示左顶点坐标,100,100表示方框长宽
ax.add_patch(plot.Rectangle((4,5),100,100,fill=False,edgecolor='red', linewidth=2))
#给方框加标注,4,5表示x,y坐标,其它相当于画笔属性
ax.text(4,5,s = "cat:90%",style='italic',bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 0})  

#在服务器中,通常没有桌面程序,则需要将figure对象转换成numpy等格式,显示在tensorboard等程序中
#将figure转换成numpy格式的函数
def fig2data(fig):
   """
       fig = plt.figure()
       image = fig2data(fig)
       @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
       @param fig a matplotlib figure
       @return a numpy 3D array of RGBA values
       """
   # draw the renderer
   fig.canvas.draw()

   # Get the RGBA buffer from the figure
   w, h = fig.canvas.get_width_height()
   buf = np.frombuffer(fig.canvas.tostring_argb(), dtype=np.uint8)
   buf.shape = (w, h, 4)

   # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
   buf = np.roll(buf, 3, axis=2)
   image = Image.frombuffer("RGBA", (w, h), buf.tostring())
   image = np.asarray(image)
   return image

#将绘制方框后的图片显示在tensorboard中
fig2data1 = fig2data(fig)  #RGBA  H,W,4
writer.add_image("image2",fig2data1,0,dataformats="HWC")

#plot.show()   #如果将结果直接显示在桌面,直接调用此句代码即可

启动tensorboard后,其绘制结果显示在tensorboard中 :
目标检测------图片预处理/方框绘图(pillow,matplotlib,tensorboard)_第1张图片

你可能感兴趣的:(目标检测)