python給圖像中物體增加bbox、文字等標記


 一、bbox與文字

方法一:使用matplotlib

import matplotlib.pyplot as plt

from PIL import Image

img_label = './A/'
img_save = './A_out/'

def draw_save(img_name):
    img_path = img_label+img_name
    img = Image.open(img_path+'.jpg')
    plt.imshow(img)
    # plt.Rectange( (left-up-x, left-up-y), width, heigt, ... )
    ax = plt.gca()
    ax.add_patch(plt.Rectangle( (100, 200), 300, 400, color="blue", fill=False, linewidth=1))
    plt.savefig(img_save+img_name+'.jpg')
    plt.clf()        # 清空畫板

draw('002')

* 假設bbox以(100, 200)為左上角點,水平width為300,垂直height為400

* 該方法得到的圖片是在一塊白色的蒙板之上的,並且默認情況下會改變圖像位深,eg:原圖為8bit位深 -> 保存圖像為24bit位深

 

方法二:使用PIL庫

from PIL import Image, ImageDraw

img = Image.open('test/00001.jpg')  # 通道順序為RGB,若為灰度圖,則 np.array(img).shape == (height, width)
draw = ImageDraw.Draw(img)
box = [233, 214, 268, 249]     # [top-left-x, top-left-y, bottom-right-x, bottom-right-y]
draw.rectangle(box)        # box must in format of [(x1, y1), (x2, y2)] or [x1, y1, x2, y2]
font = ImageFont.truetype('song-simsun.ttc', 50)    # font-size: 50
draw.text(positon, text, text-color, font=font)    # position: up-left, eg:(x1, y1)
img.save('exam.jpg')     # save to current directory

** draw.rectangle 可以使用參數outline='red'設置邊框線為紅色,默認是白色。

** 該方法保存的圖片不會改變原圖的位深

 

方法三:使用opencv庫,cv2  ——參考博客

import cv2

img = cv2.imread('grain.jpg')
img = cv2.rectangle(img, (10,50), (50,100), (0,255,0), 2)    # (img, (top-left-x, top-left-y), (bottom-right-x, bottom-right-y), color, line_width)
# equals to "cv2.rectangle(img, (10,50), (50,100), (0,255,0), 2)"

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'text', (50, 50), font, 1, (0,0,255), 1)  # (img, text, (bottom-left-x, bottom-left-y), font_size, color, font_line_width)

cv2.imwrite('./cvtest.jpg')

* cv2.imread默認讀入RGB三通道的圖像,灰度圖像也會轉換為三通道的對象

* cv2.imread對象和PIL.Image對象間的轉換方法  ——參考博客

# PIL.Image -> cv2
img = cv2.cvtColor(np.asarray(pil_img), cv2.COLOR_RGB2BGR)  # must use np.asarray() or np.array() to transfer # cv2 -> PIL.Image
img = Image.fromarray(cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB))

 

二、點

cv2.circle(img, (x, y), 1, (0, 255, 0), 1)    # (x, y) of center, raduis, color, thickness of line(if -1,then a filled circle)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM