一、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)