⽬标检测------图⽚预处理⽅框绘图(pillow,matplotlib,tensorb。。。
实验环境: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。
读⼊图⽚:
在⽬标检测任务中,通常会将⼀张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格式
。更多使⽤⽅法参见 。
matplotlib绘图并加上⽅框标注,将结果显⽰在tensorboard中
通常在⽬标检测任务,需要将最终的预测结果绘制⽅框后进⾏可视化展⽰,通常采⽤matplotlib库进⾏处理,有时并且还会将结果显⽰在tensorboard中进⾏可视化。
, ,
注: 下⾯代码⽤到了上⾯代码的变量。若要使⽤plot.show(),则要放在tensorboard写⼊完成后使⽤,否则可能会报错。
import matplotlib
#matplotlib.use('Agg')  #采⽤Agg作为matplotlib绘制后端,是⼀种⾮交互式的后端,调⽤plot.show()后不会在桌⾯显⽰图⽚,在⽆桌⾯程序的服务器中运⾏程序时可使⽤此代码。
from matplotlib import pyplot as plot
from sorboard 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表⽰⽅框长宽
matplotlib中subplot
ax.add_patch(plot.Rectangle((4,5),100,100,fill=False,edgecolor='red', linewidth=2))
#给⽅框加标注,4,5表⽰x,y坐标,其它相当于画笔属性
<(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 = _width_height()
buf = np.frombuffer(string_argb(), dtype=np.uint8)
buf.shape =(w, h,4)
# string_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), string())
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中 :

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。