Python OpenCV 畫矩形 rectangle

本篇將介紹如何使用 OpenCV 與 Python 來畫矩形 rectangle,在寫 Python 影像處理程式時常會用到 OpenCV cv2.rectangle 畫矩形的功能,接下來介紹怎麼使用 Python 搭配 OpenCV 模組來畫矩形 rectangle。

使用範例

詳細程式碼如下:

opencv-rectangle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import numpy as np

# Create a blank 640x480 black image
image = np.zeros((480, 640, 3), np.uint8)
# Fill image with gray color(set each pixel to gray)
image[:] = (128, 128, 128)

red_color = (0, 0, 255) # BGR
cv2.rectangle(image, (100, 100), (400, 200), red_color, 3, cv2.LINE_AA)

cv2.imshow('Result', image)
cv2.waitKey(0)

結果如下圖所示:

函式用法與參數解釋:
cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]])
img – Image.
pt1 – Vertex of the rectangle.
pt2 – Vertex of the rectangle opposite to pt1 .
rec – Alternative specification of the drawn rectangle.
color – Rectangle color or brightness (grayscale image).
thickness – Thickness of lines that make up the rectangle. Negative values, like CV_FILLED , mean that the function has to draw a filled rectangle.
lineType – Type of the line. See the line() description.
shift – Number of fractional bits in the point coordinates.

cv2.rectangle 參數的詳細細節請參考這裡

範例. 用 rectangle 繪製物件偵測的範圍

用 OpenCV 作物件偵測時,需要將物件框選標示出來,並且顯示該物件的範圍與標籤名稱,這在物件偵測中還蠻實用且常用到的功能,

opencv-drawBoundingBox.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import numpy as np

def drawBoundingBox(img, bboxs):
for box in bboxs:
x1,y1,x2,y2 = (box['x1'], box['y1'], box['x2'], box['y2'])
label = box['label']
cv2.rectangle(img, (x1,y1), (x2,y2), (0,255,0), 6)
fontFace = cv2.FONT_HERSHEY_COMPLEX
fontScale = 0.5
thickness = 1
labelSize = cv2.getTextSize(label, fontFace, fontScale, thickness)
_x1 = x1 # bottomleft x of text
_y1 = y1 # bottomleft y of text
_x2 = x1+labelSize[0][0] # topright x of text
_y2 = y1-labelSize[0][1] # topright y of text
cv2.rectangle(img, (_x1,_y1), (_x2,_y2), (0,255,0), cv2.FILLED) # text background
cv2.putText(img, label, (x1,y1), fontFace, fontScale, (0,0,0), thickness)
return img

# Create a blank 640x640 black image
image = np.zeros((480, 640, 3), np.uint8)
# Fill image with gray color(set each pixel to gray)
image[:] = (128, 128, 128)

bboxs = []
box = {}
box['label'] = 'object 1'
box['x1'] = 40
box['y1'] = 40
box['x2'] = 180
box['y2'] = 180
bboxs.append(box)
box2 = {'label': 'object 2', 'x1': 300, 'y1': 200, 'x2': 600, 'y2': 440}
bboxs.append(box2)
drawBoundingBox(image, bboxs)

cv2.imshow('Result', image)
cv2.waitKey(0)

結果如下圖所示:

其它相關文章推薦
Python OpenCV 畫線條 line
Python OpenCV 畫圓 circle
Python OpenCV 畫橢圓 ellipse
Python OpenCV 畫多邊形 polylines
Python OpenCV 繪製文字 putText