python给一幅图片上画矩形框并保存

方法一:cv2画框

import numpy as np
import os,cv2

im_file = os.path.join('E:\测试视频01', 'frame1.jpg')
    im = cv2.imdecode(np.fromfile(im_file, dtype=np.uint8), -1)
    class_name = 'people'
    dets = [
        [1,1,1566.7317,556.5099,107.32471,109.541504,0.9994748,-1,-1,-1]
            ]
    obj01 = dets[0][2:6]
    score = dets[0][6]
    #画框
    # cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)参数img为原图,左上角坐标,右下角坐标,线的颜色,线宽
    cv2.rectangle(im, (int(obj01[0]), int(obj01[1])), (int(obj01[2]+obj01[0]), int(obj01[3]+obj01[1])), (0, 0, 255), 2)
    #画圆
    #cv2.circle(im, (100, 100), 10, (0, 0, 255), -1)#图片,圆心坐标,半径,颜色,-1代表实心圆
    # 添加文本cv2.putText(img, str(i), (123, 456)), font, 2, (0, 255, 0), 3)
    # 各参数依次是:图片,添加的文字,左上角坐标,字体,字体大小,颜色,字体粗细
    cv2.putText(im,'{:.3f}'.format(score), (int(obj01[0]), int(obj01[1])), cv2.FONT_HERSHEY_COMPLEX, 1.3, (255,0,255), thickness=2)
    # cv2.imshow('head', im)
    #保存画框后的图片
    save_path = "E:/测试/frameTest.jpg"
    cv2.imencode('.jpg', im)[1].tofile(save_path)

方法二:plt画框

import matplotlib.pyplot as plt
import numpy as np
import os

im_file = os.path.join('E:\测试视频01', 'frame1.jpg')
    im = cv2.imdecode(np.fromfile(im_file, dtype=np.uint8), -1)
    im = im[:, :, (2, 1, 0)]
    class_name = 'people'
    dets = [
        [1,1,1566.7317,556.5099,107.32471,109.541504,0.9994748,-1,-1,-1]
            ]
    obj01 = dets[0][2:6]
    score = dets[0][6]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    bbox = dets[0][2:6]
    score = dets[0][6]

    ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2],
                          bbox[3], fill=False,
                          edgecolor='red', linewidth=3.5)
            )
    #画圆
    #ax.add_patch(
     #       plt.Circle((bbox[0], bbox[1]),5,fill=True,edgecolor='red',linewidth=3.5)
      #  )
    ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    save_path = 'E:\测试/frameTest.jpg'
    plt.savefig(save_path)  # path为你将保存图片的路径
    plt.draw()
    plt.show()

 

你可能感兴趣的:(python)