opencv-python繪製圖片標註框

參考自簡書Python實現一個簡單的圖片物體標註工具

簡化版實現


import os
import cv2
from tkinter.filedialog import askopenfilename

class SimpleLabel:
    
    color = (255, 255, 255)
    FPS = 24
    KEY_DELETE = 46
    KEY_ENTER = 13
    KEY_EXIT = 27

    def __init__(self, window_name='SimpleLabel'):
        self.window_name = window_name
        self.bboxes = []
        self._drawing = True
        self._lu = None
        self._rd = None
        self._drawing = False
    
    def __repr__(self):
    	return "SimpleLabel(window_name={}, bboxes={})".format(self.window_name, self.bboxes)

    def _mouse_ops(self, event, x, y, flags, param):
        if event == cv2.EVENT_RBUTTONDOWN:
            self._drawing = True
            self._lu = (x, y)
        elif event == cv2.EVENT_RBUTTONUP:
            self._drawing = False
            self._rd = (x, y)
            self.bboxes.append((self._lu, self._rd))
        elif event == cv2.EVENT_MOUSEMOVE:
            self._rd = (x, y)
        elif event == cv2.EVENT_LBUTTONDBLCLK:
            if self.bboxes:
                self.bboxes.pop()

    def _draw_bboxes(self, img):
        for box in self.bboxes:
            cv2.rectangle(img, box[0], box[1], color=SimpleLabel.color, thickness=2)
        if self._drawing:
            cv2.rectangle(img, self._lu, self._rd, color=SimpleLabel.color, thickness=2)
        return img

    @staticmethod
    def set_color(color):
        SimpleLabel.color = color
    
    def start(self, img_path):
        if not os.path.exists(img_path):
            return
        img = cv2.imread(img_path, 1)
        cv2.namedWindow(self.window_name, 0)
        cv2.setMouseCallback(self.window_name, self._mouse_ops)
        cv2.imshow(self.window_name, img)
        
        key = 0
        delay = int(1000 / self.FPS)
        while key != self.KEY_ENTER:
            im = img.copy()
            im = self._draw_bboxes(im)
            cv2.imshow(self.window_name, im)
            key = cv2.waitKey(delay)
            print(key)
        cv2.destroyAllWindows()

if __name__ == '__main__':
    img_path = askopenfilename(title='Where is the images?', 
                               initialdir=r'E:\image_root', 
                               filetypes=[('', '*.JPEG'), ('', '*.tiff'), ('All Files', '*')])
    slwin = SimpleLabel()
    slwin.set_color((255, 255, 0))
    slwin.start(img_path)
    print(slwin)

給圖片繪製預測框

import numpy as np
from matplotlib import pyplot as plt

import cv2

COCO_INSTANCE_CATEGORY_NAMES = [
    '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
    'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
    'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
    'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
    'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
    'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
    'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
    'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
    'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
    'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
    'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
    'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
]

def visualize(images, predictions, topk=3):
    
    for image, pred in zip(images, predictions):
        image = (np.transpose(image.numpy(), [1, 2, 0])*255).astype(np.uint8)
        boxes = pred[0]['boxes']
        labels = [COCO_INSTANCE_CATEGORY_NAMES[idx] for idx in pred[0]['labels']]
        scores = pred[0]['scores']
        image = overlay_results(image, boxes, labels, scores, topk)
        plt.figure()
        plt.imshow(image)

def overlay_results(image, boxes, labels, scores, topk):
    template = "{}: {:.2f}"
    for i, (box, label, score) in enumerate(zip(boxes, labels, scores), 1):
        if i > topk:
            break
        x, y = box[:2]
        s = template.format(label, score)
        cv2.putText(image, s, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1., (255, 255, 255), 2)
        image = cv2.rectangle(image, tuple(box[:2]), tuple(box[2:]), (255, 255, 255), 2)
    return image[:, :, ::-1]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章