python中显示图片和文字
这里的实现方法有两种:一种是python结合opencv实现;一种是python自带的matplot工具来实现的。
- python+opencv实现
- python+matplot实现
python+opencv实现
opencv实现主要就是利用opencv图像相关函数显示就可以了。在这里主要记录一下在图像中添加文字的部分。
==。python不是很熟,所以需要记录一下。
直接贴代码(这里只是部分代码,并不完整):
import cv2 as cv
if args.print_results:
with open(args.labels_file) as f:
labels_df = pd.DataFrame([{'synset_id':l.strip().split(' ')[0], 'name': ' '.join(l.strip().split(' ')[1:]).split(',')[0]}for l in f.readlines()])
labels = labels_df.sort('synset_id')['name'].values
count=0
cv.namedWindow("googlenet_demo",1)
#cv.resizeWindow("googlenet_demo",800,800)
for im_file in glob.glob(args.input_file + '/*.' + args.ext):
image=cv.imread(im_file)
indices =(-scores[count]).argsort()[:5]
predictions = labels[indices]
meta = [(p, '%.5f' % scores[count][i]) for i,p in zip(indices, predictions)]
metaa=meta[0]
cv.putText(image, ('prediction top-5 result:') , (5,15), cv.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255), 1, 8,0)
cv.putText(image, ('%s %s' % metaa) , (7,30), cv.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255), 1, 8,0)
cv.imshow('googlenet_demo', image)
print im_file, meta
count += 1
key = cv.waitKey()
cv.destroyWindow('googlenet_demo')
主要实现的功能是将待识别的图像显示出来并在图片上加入分类的结果。
cv.putText()参数解释:
void cv::putText(
cv::Mat& img, // 待绘制的图像
const string& text, // 待绘制的文字
cv::Point origin, // 文本框的左下角
int fontFace, // 字体 (如cv::FONT_HERSHEY_PLAIN)
double fontScale, // 尺寸因子,值越大文字越大
cv::Scalar color, // 线条的颜色(RGB)
int thickness = 1, // 线条宽度
int lineType = 8, // 线型(4邻域或8邻域,默认8邻域)
bool bottomLeftOrigin = false // true='origin at lower left'
);
该函数所支持的字体:
最终结果:
python+matplot实现
实现代码
if args.print_results:
with open(args.labels_file) as f:
labels_df = pd.DataFrame([{'synset_id':l.strip().split(' ')[0], 'name': ' '.join(l.strip().split(' ')[1:]).split(',')[0]}for l in f.readlines()])
labels = labels_df.sort('synset_id')['name'].values
count=0
for im_file in glob.glob(args.input_file + '/*.' + args.ext):
image= mpimg.imread(im_file)
indices =(-scores[count]).argsort()[:5]
predictions = labels[indices]
meta = [(p, '%.5f' % scores[count][i]) for i,p in zip(indices, predictions)]
metaa =meta[0]
plt.ion()
plt.imshow(image)
plt.text(5, 10, "prediction top-5 result:", size = 10, family = "fantasy", color = "r", style = "italic", weight = "light",
bbox = dict(facecolor = "r", alpha = 0.2))
plt.text(10, 25, ('%s %s' % metaa), size = 10, family = "fantasy", color = "r", style = "italic", weight = "light")
plt.show()
plt.pause(5)
plt.close()
print im_file, meta
count += 1
plt.text()参数解释:
# 第一个参数是x轴坐标
# 第二个参数是y轴坐标
# 第三个参数是要显式的内容
# alpha 设置字体的透明度
# family 设置字体
# size 设置字体的大小
# style 设置字体的风格
# wight 字体的粗细
# bbox 给字体添加框,alpha 设置框体的透明度, facecolor 设置框体的颜色
plt.text(-3, 20, "function: y = x * x", size = 15, alpha = 0.2)
plt.text(-3, 40, "function: y = x * x", size = 15, family = "fantasy", color = "r", style = "italic", weight = "light", bbox = dict(facecolor = "r", alpha = 0.2))
最终结果: